Skip to content

Instantly share code, notes, and snippets.

@ycku
Created August 24, 2020 09:48
Show Gist options
  • Save ycku/e1a07a0d81674c4cefbb9caec6f76e94 to your computer and use it in GitHub Desktop.
Save ycku/e1a07a0d81674c4cefbb9caec6f76e94 to your computer and use it in GitHub Desktop.
Change/Fix the permissions after creating user's directory
$target_dir = "d:\temp"
# WHERE for safe test
# Process the whole directories by removing WHERE clause
$target_list = Get-ChildItem $target_dir | WHERE { $_.name -eq "00123456" }
foreach ($userdir in $target_list) {
$userdir.Fullname
$ACL = Get-ACL $userdir.Fullname
# Disable inheritance
$ACL.SetAccessRuleProtection($True, $False)
# Remove all permissions
foreach ($access in $ACL.access) {
$ACL.RemoveAccessRule($access) | Out-Null
}
# Right owner is the same name as the name of userdir
$Owner = New-Object System.Security.Principal.NTAccount("DOMAINXX", $userdir.name)
$ACL.SetOwner($Owner)
# Set "Administrators" for FullControl
$fileSystemAccessRuleArgumentList = "Administrators", "FullControl", "Allow"
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$ACL.SetAccessRule($fileSystemAccessRule)
# Set "SYSTEM" for FullControl
$fileSystemAccessRuleArgumentList = "SYSTEM", "FullControl", "Allow"
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$ACL.SetAccessRule($fileSystemAccessRule)
# Set the target domain user for FullControl
$fileSystemAccessRuleArgumentList = ("DOMAINXX\"+$userdir.name), "FullControl", "Allow"
$fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList
$ACL.SetAccessRule($fileSystemAccessRule)
# Set ACL to the user's directory
Set-Acl -Path $userdir.Fullname -AclObject $ACL
# Set ACL the the sub-directories recursively
Get-ChildItem -Path $userdir.Fullname -Recurse -Force | Set-Acl -AclObject $ACL | Out-Null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment