Here’s something I had to do at work a few weeks back. I wanted to blog about it since then but never got around to it.
We had copied a bunch of folders from one location to another. Since this was a copy the folders lost their original ACLs. I wanted to do two things – 1) the folder names were in the format “LastName, FirstName” and I wanted to change that to “username” (I had a CSV file with mappings so I could use that to do the renaming). 2) I wanted to change the ACLs so the user had modify rights to the folders.
For the first task here’s what I did:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$Mappings=@{} foreach($r in (Import-Csv \path\to\Mappings.csv)) { $Mappings[$r.Olduser]=$r.NewUser } foreach ($folder in "G:\Folder1","G:\Folder2") { Get-ChildItem $folder -Directory | %{ $oldPath = $_.FullName; $oldUser = Split-Path -Leaf $oldPath; $newUser = $Mappings[$oldUser]; if ($newUser -ne $null) { $newPath = "G:\NewFolder\$newUser" # Write-Host "Will move from $oldPath to $newPath" Move-Item $oldPath $newPath } } } |
Note that apart from renaming I also move the folder to a different path (coz I had multiple source locations and wanted to combine them all into one).
For the second task here’s what I did:
1 2 3 4 5 6 7 8 9 |
$HomeFolders = Get-ChildItem G:\NewFolder -Directory foreach ($HomeFolder in $HomeFolders) { $Path = $HomeFolder.FullName $Acl = (Get-Item $Path).GetAccessControl('Access') $Username = $HomeFolder.Name $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow') $Acl.SetAccessRule($Ar) Set-Acl -path $Path -AclObject $Acl } |
Later on I realized the folders still had the BUILTIN\Users
entity with full control so I had to remove these too. The code for that was slightly different so here goes:
1 2 3 4 5 6 7 8 9 10 |
$HomeFolders = Get-ChildItem G:\NewFolder -Directory foreach ($HomeFolder in $HomeFolders) { $change = $false; $Path = $HomeFolder.FullName $Acl = (Get-Item $Path).GetAccessControl('Access') foreach ($value in $Acl.Access) { if ($value.IdentityReference -eq "BUILTIN\Users") { $Acl.RemoveAccessRule($value); $change=$true; } } if ($change) { Set-Acl -Path $Path -AclObject $Acl } } |
This is a good article on what I was doing above. And this TechNet article is a useful resource on the various rights that can be assigned.