Search code examples
powershellnetwork-programmingpermissionsaccount

Powershell - New User home folder permissions


I am working on a PS script to automate new network accounts, their home folder and exchange mailbox. We have multiple Domain controllers so am looking for a way of creating a network account on one domain controller but creating the home directory on a different site with its own domain controller. I have tried this but when setting permissions an issue has occurred because the account has not replicated over to the other DC. Anyone have any ideas to get around this?

New Account Function

Function New-BVStandardUser
{
    Param (
        $FirstName,
        $LastName,
        $CallRef,
        $SiteName,
        $EmployeeID,
        $ExpiryDate,
        $InternetAccess,
        $ExternalEmailAccess
    )

    $ImportGroups = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteGroups.csv" -Delimiter ","
    $ImportServers = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteServers.csv" -Delimiter ","
    $ImportOUs = Import-Csv -Path "\\UKSP-FS01\Lawsonja$\Scripts\New-ADUser\SiteOUs.csv" -Delimiter ","

    # Convert the first and last name so it does not have special characters for the email address/ UPN
    $LastNameEdit = $LastName -replace '[^a-zA-Z]', ''
    $FirstNameEdit = $FirstName -replace '[^a-zA-Z]', ''

    # Fetch a free username from AD based on the provided first and last name from the user
    $Username = Get-ADUsername -FirstName $FirstNameEdit -LastName $LastNameEdit

    # Generate a random password using the imported module
    $Password = Get-Randompassword  

    # Create the AD account based on the inputted fields
    $Params = @{
        DisplayName = "$($LastName), $($FirstName)"
        DirectoryName = "$($LastName), $($FirstName)"
        SamAccountName = "$Username"
        UserPrincipalName = "$FirstNameEdit.$LastNameEdit@Bakkavor.com"
        Comment = "Created $($env:USERNAME) - $(Get-Date -Format dd/MM/yy) - $($CallRef)"
        GivenName = "$FirstNameEdit"
        Surname = "$LastNameEdit"
        Description = "$($SiteName) User"
        Enabled = $true
        ChangePasswordAtLogon = $true
        Path = "$ImportOUs.$($SiteName)"
        HomeDirectory = "\\$ImportServers.$($SiteName)\$Username$"
        HomeDrive = "U"
        AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
    }

    try
    {
        New-ADUser @Params -ErrorAction Stop
        Write-Verbose -Verbose "Network Account Created"
    }
    catch
    {
        Write-Warning "Error creating network account. Error: $($_.Exception.Message)"
        break
    }

New Home Drive Function

Function New-BVUDrive
{
Param
(
    $Username,
    $Server
)

# Connect to the relevant server in CSV, create new folder, create new SMB Share for the user and add share/ NTFS permissions
    Invoke-Command -ComputerName $Server -ArgumentList $Username -ErrorAction Stop -ScriptBlock 
    {
        param($Username)  

        $FindShare = (Get-SmbShare -Name Users$).Path

        if($FindShare -eq $true)
        {

            try
            {
                New-Item -ItemType Directory -Path "$FindShare\$Username" -ErrorAction Stop
                New-SmbShare -Name "$Username$" -Path "$FindShare\$Username" -FullAccess "AD\Server Admins", "AD\Domain Admins" -ChangeAccess "AD\$Username" -ErrorAction Stop

                $Acl = Get-Acl "$FindShare\$Username"

                foreach($Rule in $Acl.Access) 
                {        
                    $Acl.RemoveAccessRule($Rule)
                }

                $Ar = New-Object  system.security.accesscontrol.filesystemaccessrule("Everyone","FullControl","Allow") 
                $Acl.SetAccessRule($Ar)

                $Acl.SetAccessRuleProtection($false, $true)

                Set-Acl "$FindShare\$Username" $Acl -ErrorAction Stop
            }
            catch
            {
                Write-Warning "U drive failed to create. Error: $($_.Exception.Message)"
            }
        }
        else
        {
            Write-Warning "Users$ share not found on server"
        }
    }
}

Solution

  • Have you tried using the SID? In the second function New-BVUDrive, replace the username with SID. and use the following cmdlet to get the SID:

    (Get-ADUser -Identity $SamAccountName).SID.Value
    

    you will be able to set the ACL now, until the data will replicate you will see in the security tab the SID, but the user will be able to access the folder if he will try.

    $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule ($SIDIdentity, 'FullControl', ('ContainerInherit','ObjectInherit'), 'None','Allow')
    

    Hope it will help.