I have made a script that has to loop through thousands of AD user home directories one by one, basically doing the following steps for each one:
- Take ownership of the folder
- Add an access rule for Domain Admin group
- Return the ownership of the folder
- Loop through all child folders and files, enabling inheritance and removing all explicit permissions
After excessive testing and problem solving the script works perfectly, except for 1 problem that has left me banging my head against a wall.
The script successfully loops about 50-150 folders (very random) and then results in the following error: "the trust relationship between the primary domain and the trusted domain failed"
I built an additional loop that will retry 30 times (every 30 seconds) when this error occurs. However this does not help as the trust relationship remains lost for as long as the script runs.
The most interesting part is, that once I run the script again, (starting from the problem-folder) the folder is processed without further error. The script never gets stuck on the same folder again. But then this happens again, say 50 folders later.
This is a HUGE inconvenience as I will need to process at least 15,000 user folders and I will always need to compile a new list of "folders left to process", when 1 fails.
Here is the basic code functionality, where I've taken out all the unnecessary error handling and retry-looping for better readability:
foreach ($folder in $homeFoldersFound) {
$accessControl = Get-Acl -LiteralPath $folder.FullName -ErrorAction Stop
#Current owner
$folderOwner = $accessControl.Owner
#Take ownership for the user running the script
$accessControl.SetOwner([System.Security.Principal.NTAccount]$currentUser)
#Access rule to add
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($groupToAdd,"FullControl","ContainerInherit,ObjectInherit", "None", "Allow")
$accessControl.AddAccessRule($accessRule)
#Purge current explicit permissions
$accessControl.SetAccessRuleProtection($true, $false)
#Apply ownership and access rules
set-acl -AclObject $accessControl -LiteralPath $folder.FullName -ErrorAction Stop | Out-Null
#Return the previous ownership and apply
$accessControl.SetOwner([System.Security.Principal.NTAccount]$folderOwner)
$accessControl.SetAccessRuleProtection($false, $false)
set-acl -AclObject $accessControl -LiteralPath $folderItem -ErrorAction Stop | Out-Null
#Loop through child items, enable inheritance & remove explicit permissions
foreach ($item in (Get-ChildItem -LiteralPath $folder.FullName -Recurse -ErrorAction Stop)) {
#More code
}
}
Again, there shouldn't really be anything wrong with the code, as the error happens so randomly and passes when running the script again. Any ideas on what might cause this / how to work around it?
All help is appreciated!