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:

$acl = Get-Acl $path
$acl | Set-Acl

$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:

$acl = Get-Acl $path
$acl.Access | %{$acl.RemoveAccessRule($_)}
$permission = "domainDomainAdmins","FullControl", "ContainerInherit,ObjectInherit","None","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl | Set-Acl

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.

New-SmbShare -Name ‘usershare$’ -Path ‘D:Usersusername’ -FullAccess (‘domainDomainAdmins’,’domainusername’)

If you want to update the users home folder path in Active Directory you can use:

Import-Module ActiveDirectory
$user = Get-ADUser -LDAPFilter "(sAMAccountName=$username)"
Set-ADUser -Identity $user -HomeDrive ‘U:’ -HomeDirectory (‘\fileserver-01’ + $username + ‘$’)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: