Monthly Archives: June 2012

Using Powershell to change USER home drive permissions

There may be times, say during migration to a new domain where you need to add permissions for users in the new domain. I used the following script, run from my Windows 7 PC using Powershell 3.0, to make the changes.

It uses a csv file with two columns, “olduser”, and “newuser”. Obviously each line has the old user ID and then new one. The script will go through each user in the file, find the folder that has the same name as the user, prompt if it can’t find it, and then add permissions on the folder for the “newuser”.

It will leave the old permissions in place, because you could be doing this during the pilot phase of the process.

Here is the code.


$folderroot = Read-Host "What is the path to USER$"
$csvfile = Read-Host "What is the path to the csvfile"

#Read contents of CSV file.
$users = Import-Csv $csvfile

If ($users) {
	Foreach ($user in $users) {
		#Read line from file, and create expected path to home drive.
		$newID = $user.newuser
		$oldID = $user.olduser
		$folderpath = $folderroot + "\" + $user.olduser
		#Get the ACL for the folder.
		$acl = Get-Acl $folderpath
		#Check that the ACL isn't empty because the expect folder doesn't exist.
		if ($acl -eq $null){
			$altpath = (Read-Host "Folder not found, please enter the folder name manually for $oldID")
			if ($altpath) {
				$folderpath = ($folderroot + "\" + $altpath)
				$acl = Get-Acl $folderpath
				}
			else {
				Write-Host "Sorry, still not found."
				}
			}
		#Build a permission to add to the ACL.	
		$permission = “IPRUK\$newID”,”Modify”,”ContainerInherit,ObjectInherit”,”None”,”Allow”
		$accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
		$acl.SetAccessRule($accessrule)
		$acl | set-acl -path $folderpath
		$timenow = get-date
		Write-Host "Permissions set for $oldID at $timenow"
		$users2 = $users | where {$_.olduser -ne $oldID}
		$users = $users2
		If ($users){
			$users | Export-Csv users.csv -NoTypeInformation
			}
		}
	}


Obviously, you need to be VERY CAREFUL about running this, as it would be a mess to clean up, and this code as it stands, is not production ready. It could really do with a bit more checking built in. It worked for me though 🙂

2 Comments

Filed under Microsoft, Powershell, Windows 2008