简体   繁体   中英

Powershell: Apply owner to multiple files and folders per username

We have a server that houses the My Documents folder for all our users. Some of the folder owner changed to administrator. I am trying to devise a PowerShell script that goes to each user's root my documents folder and applies the user as the owner for all the sub folders and files with in it. Is this Possible?

I have the following from a previous script that attempted to set the user as full permissions per each my document root folder:

$FolderPath = "E:\mydocuredir\"
$MyDocsMain = Get-ChildItem -Path $FolderPath -Directory

Get-ChildItem -Path $FolderPath -Directory | ForEach-Object{

    $HomeFolders = Get-ChildItem $FolderPath $_.Name -Directory

    $Path = $HomeFolders.FullName
    $Acl = (Get-Item $Path).GetAccessControl('Access')
    $Username = $_.Name

    $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'FullControl', 'ObjectInherit', 'InheritOnly', 'Allow')
    $Acl.SetAccessRule($Ar)
    Set-Acl -path $Path -AclObject $Acl
}

Firstly ensure that the share and root folder permissions for redirected folders follow best practice .


I would use the NTFSSecurity PS Module ( blog on its use ). This module has commands that are much easier to understand as they follow they way your would set permissions via the GUI.

$FolderPath = "E:\mydocuredir"

Get-ChildItem -Path $FolderPath -Directory | ForEach-Object{
    Add-NTFSAccess -Path $_.FullName -Account "domain\$($_.Name)" -AccessRights FullControl -AppliesTo ThisFolderSubfoldersAndFiles
}

To set Owner, replace the Add-NTFSAccess command with:

Set-NTFSOwner -Path $_.FullName -Account "domain\$($_.Name)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM