Powershell: Manage folder permissions

Working with folder and share security is to often treated as set and forget. A good practice is to run daily jobs to check, report and reset permissions on shared folders and home directories. There are several ways to do this but it can easily be done from Powershell. This can also be used when migrating between servers and access needs to be added or removed. Here is a few useful code snippets when working with folder access and shares in Powershell.
When new folders are created they may inherit unwanted rights. To disable inheritance use this:
[ps]
$acl = Get-Acl $path
$acl.SetAccessRuleProtection($true,$true)
$acl | Set-Acl
[/ps]
$path is replaced with whatever path you are working with.
To remove all access rules in the ACL to start with a clean slate, use this:
[ps]
$acl = Get-Acl $path
$acl.Access | %{$acl.RemoveAccessRule($_)}
$permission = "domainDomainAdmins","FullControl", "ContainerInherit,ObjectInherit","None","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl
[/ps]
Again $path replaces whatever path your working with. It’s good to set at least one permission after clearing the ACL so you don’t lose control over the folder and have to force your way back. You can use the same code to add access for any user or group by leaving out the RemoveAccessRule part.
Creating a share is also easy from Powershell.
[ps]
New-SmbShare -Name ‘usershare$’ -Path ‘D:Usersusername’ -FullAccess (‘domainDomainAdmins’,’domainusername’)
[/ps]
If you want to update the users home folder path in Active Directory you can use:
[ps]
Import-Module ActiveDirectory
$user = Get-ADUser -LDAPFilter "(sAMAccountName=$username)"
Set-ADUser -Identity $user -HomeDrive ‘U:’ -HomeDirectory (‘\fileserver-01’ + $username + ‘$’)
[/ps]