After spending half a day to create a Powershell script to set owner rights on the home folders of our users, I found out Powershell is unable to set owner permissions by showing the error “The security identifier is not allowed to be the owner of this object” every time.
So the Powershell script below won’t work for me and I decided to try it the old fashion way: cmd with icacls.
In no less then a hour I had a working script with just three effective lines. The cmd scripts first creates a list of user folders and puts them in a text file. Then each line from the text file is being read and by using icacls the ownership of each folder is changed to the appropriate user. The only condition is that your user folder name must be the same as the user account, which is usually the case with user folders such as home or profile folders.
CMD script:
@echo off REM Create list of folders dir /a:d /b X:\users >C:\temp\users.txt REM Read each line from just created text file... for /f "tokens=*" %%G in (C:\temp\users.txt) do ( REM ...and set ownership for each folder icacls "X:\Users\%%G" /setowner "domainname\%%G" echo. )
Powershell script:
# Home drive folder
$homeDrivesDir="X:\Users"
# Your domain name
$domainName = "domainname"
#Save work directory
pushd .
# Location homedrive
set-location $homeDrivesDir
# For every folder in the $homeDrivesDir folder
foreach($homeFolder in (Get-ChildItem $homeDrivesDir | Where {$_.psIsContainer -eq $true})) {
# Place ACL in a variable
$Acl = (Get-Item $homeFolder).GetAccessControl("Access")
Write-host "Settings rights for:" $homeFolder
# Create the Access Rule
$acct=New-Object System.Security.Principal.NTAccount($domainName,$homeFolder.name)
Write-host "Owner of folder will be:" $acct
Write-host ""
# Apply the access rule to the ACL
$Acl.SetOwner($acct)
Set-Acl $homeFolder.FullName $Acl
Get-Acl $homeFolder.FullName | Format-List
}
# Cleanup
popd

