Programmatically set folder/file ownership recursively

Recently, I had the task of unraveling a messy file system for a customer. Their permissions were not well maintained and individual folder ownership was set to various deleted accounts or missing altogether. So, I created a script that would clean the ownership bit up, thus allowing an administrator to at least see what is happening to the folders and files.

<#
Purpose:	Script to set ownership on a folder and it's subfolders/files
Author:		Michael Kenning (mjkenning@gmail.com)
Version:	1.0 (17 JUNE 2014)

Notes:		

Possible Rights to assign via ACL:
	AppendData
	ChangePermissions
	CreateDirectories
	CreateFiles
	Delete
	DeleteSubdirectoriesAndFiles
	ExecuteFile
	FullControl
	ListDirectory
	Modify
	Read
	ReadAndExecute
	ReadAttributes
	ReadData
	ReadExtendedAttributes
	ReadPermissions
	Synchronize
	TakeOwnership
	Traverse
	Write
	WriteAttributes
	WriteData
	WriteExtendedAttributes
#>

$DomainName =  "[Domain Name]"
$HomeDirectoryPath = "\\[Servername]\E$\Users"
$SubDirectories = (Get-ChildItem $HomeDirectoryPath)

Foreach ($FolderName in $SubDirectories) {
	$owner = New-Object System.Security.Principal.NTAccount('BUILTIN\Administrators')
	$objUser = New-Object System.Security.Principal.NTAccount("$DomainName","$FolderName")
	
	#Set Parent Folder Ownership
	Get-Item -LiteralPath "$HomeDirectoryPath\$FolderName" -ErrorAction SilentlyContinue | Get-Acl |
	ForEach-Object {
		$_.SetOwner($owner) 
		Set-Acl -aclobject $_ -Path $_.PSPath
		$Path = Split-Path $_.Path -NoQualifier
		Write-Host $Path "Folder Owner Set -" $owner
	}
	#Set Child Item Ownership
	Get-ChildItem -LiteralPath "$HomeDirectoryPath\$FolderName" -Recurse –ErrorAction SilentlyContinue | Get-Acl | 
	ForEach-Object {
		$_.SetOwner($owner) 
		Set-Acl -aclobject $_ -Path $_.PSPath
		$Path = Split-Path $_.Path -NoQualifier 
		Write-Host $Path "File Owner Set -" $owner
		}
}
Advertisements
Tagged with: ,
Posted in Powershell

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: