Powershell – ICACLS in powershell script 50% working

icaclspermissionspowershell

I have an ICACLS command running within a powershell script. The script creates a new folder on a server share, creates a new security group in AD and then runs ICACLS to provision the folder. When I execute the function, sometimes it works and sometimes it doesn't. In testing, only 50% of the time does the ICACLS command work successfully.

New-ADGroup -Name "Group Name" -GroupCategory Security -GroupScope Global -SamAccountName "Group Name" -Description "Security Group" -Path "OU=Accounts,DC=Contoso,DC=COM"
New-Item -Path "\\Server1\ServerShare\" -Name "Group Share" -ItemType directory
icacls "\\Server1\ServerShare\Group Share" /Inheritance:r /T /Grant:R "Group Name"

icacls : Group Name: No mapping between account names and security IDs
was done.
+ CategoryInfo :NotSpecified: (Group Name…y IDs was done. :String) [], RemoteException
+ FullyQualifiedErrorID : NativeCommandError

Best Answer

I coded the script to look for an error and take action. I store the results of the ICACLS command in $Results. If $Results is an error, it will display Write-Host "Pausing 5 seconds for AD replication" message and try the command again. Thanks for the tip @Ryan.

I tried to mask the "No Mapping between account names and security IDs was done." red error message with a Try/Catch construct, but no luck. I assume Try/Catch does not work because it is a DOS command. Nevertheless, the script continues as soon as replication completes. I could increase the wait time to 10 seconds and decrease the number of error messages the script displays. I don't want the admin to think something is wrong and usually red error messages means just that.

Do
{
     $Results = icacls "\\Server1\ServerShare\Group Share" /Inheritance:r /T /Grant:R "Group Name"
     If ($Results -eq 'Successfully processed 0 files; Failed processing 1 files')
     {
          # We just saw a RED ERROR message.
          Write-Host "Pausing 5 seconds for AD replication"
          Start-Sleep 5
     }
} While ($Results -eq 'Successfully processed 0 files; Failed processing 1 files'}