Wednesday, December 11, 2013

Everyday Powershell - Part 12 - Change the owner of all files in a folder

This is the next part in an ongoing series about Powershell. You may have heard about how awesome Powershell is but have struggled to find ways to make it useful in your day to day work. That's what this series is going to address. It'll provide scripts and knowledge to address practical everyday problems

This one was another request. We love requests please send more!

The reader wanted a script that would recursively set  the owner of all files in a folder.

As usual the scripting guys are all over this kind of thing.
http://blogs.technet.com/b/heyscriptingguy/archive/2008/04/15/how-can-i-use-windows-powershell-to-determine-the-owner-of-a-file.aspx

Our contribution was putting it in a loop and adding a progress indicator. Vital sanity proofing if you are going to watch this thing as it runs over thousands of files...
$path = c:\test
$objUser = New-Object System.Security.Principal.NTAccount("SOMEDOMAIN", "SOMEUSER")

$list = get-childitem $path -recurse
$count = $list.count
$i = 0

foreach ($file in $list)
{
    $i++
    $prog = ($i/$count* 100
    Write-Progress -Activity "Processing" -percentcomplete $prog -Status $file.fullname
    $objFile = Get-Acl $file.fullname
    $objFile.SetOwner($objUser)
    Set-Acl -aclobject $objFile -path $file.fullname
}

Working with Access Control Lists is a bit funny. We can't just add things to the ACL we've got make a copy of it;
$objFile = Get-Acl $file.fullname

Perform the modification;
$objFile.SetOwner($objUser)

and then apply it to the file as a new ACL.
Set-Acl -aclobject $objFile -path $file.fullname 

No comments:

Post a Comment