Set homefolder permissions with PowerShell

imageToday one of my collegues asked me to write a script that performs two actions for all users of a certain Organizational Unit:

  1. Ensure that each user has modify permissions on their homefolder
  2. Make each user visible in the Exchange Address List.

Sounds like a PowerShell job right?

I reused my function to set NTFS Permissions by SID:

function SetNTFSPermissionsBySid([string]$directory, [System.DirectoryServices.DirectoryEntry]$objAD)
    # Convert byte array sid to sid string
    $sID = New-Object System.Security.Principal.SecurityIdentifier $objAD.objectsid[0],0

    # Inheritance This Folder, Subfolders and Files)
    $inherit = []"ContainerInherit, ObjectInherit"
    $propagation = []"None"

    # Retrieve the ACL
    $aCL = Get-Acl $directory

   # Create Ace
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($sID, "Modify", $inherit, $propagation, "Allow")

   # Add Ace to Acl

   # Set Acl to the directory
    Set-Acl -aclobject $aCL -path $directory

And then I only needed to get the OU and do a foreach loop on it’s children:

$OU = [ADSI]"LDAP://OU=TheOU,OU=Employees,DC=contoso,DC=com"
foreach ($User in $OU.Children)
		# Grant Modify Permissions to the user on his homedirectory as specified in AD
                SetNTFSPermissionsBySid $User.HomeDirectory $User

		# Unhide the user from the Exchange Address List
                $User.msExchHideFromAddressLists = $false