2015-05-26 22 views
0

創建腳本以遞歸方式更改整個目錄的ACL。這個簡單的腳本相應更改一個文件的ACL,但是我不知道該怎麼對Get-ChildItem如何在Get-ChildObject的每個輸出上運行腳本

Get-ChildItem $directory –recurse | % { Write-host $_.FullName } 

此輸出目錄/文件名的相應表中每個文件運行腳本

$acl = Get-Acl $file 
$permission = "domain/user","FullControl","Allow" 
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission 
$acl.SetAccessRule($accessRule) 
$acl | Set-Acl $file 

有沒有辦法將Get-ChildItem的每個輸出設置爲$file?我試圖在ForEach-Object上閱讀,但我沒有能夠正確的語法。

回答

0

你可以試試這個

Get-Childitem $directory | ForEach { 
    $file = $_ 
    $acl = Get-Acl $file 
    $permission = "domain/user","FullControl","Allow" 
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission 
    $acl.SetAccessRule($accessRule) 
    $acl | Set-Acl $file 
} 
1

您可以嵌入你已經在foreach循環的代碼。

$files = Get-ChildItem $directory -recurse 

foreach($file in $files) { 
    $acl = Get-Acl $file 
    $permission = "domain/user","FullControl","Allow" 
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission 
    $acl.SetAccessRule($accessRule) 
    $acl | Set-Acl $file 
} 
0

我會簡單地使用當前對象變量($_):

Get-ChildItem $directory –Recurse | % { 
    $acl = Get-Acl -LiteralPath $_ 
    $permission = 'domain\user', 'FullControl', 'Allow' 
    $accessRule = New-Object Security.AccessControl.FileSystemAccessRule $permission 
    $acl.SetAccessRule($accessRule) 
    Set-Acl -AclObject $acl -LiteralPath $_ 
} 

,如果你只是由Get-ChildItem調用的輸出分配給一個變量首先得到文件數組想要將ACL修改放入一個腳本中,並將其與Get-ChildItem分離它我建議使腳本process pipelined input

[CmdletBinding()] 
Param(
    [Parameter(
    Mandatory=$true, 
    ValueFromPipeline=$true, 
    ValueFromPipelineByPropertyName=$true 
)] 
    [IO.FileSystemInfo]$Path 
) 

Begin { 
    $permission = 'domain\user', 'FullControl', 'Allow' 
    $accessRule = New-Object Security.AccessControl.FileSystemAccessRule $permission 
} 

Process { 
    $acl = Get-Acl -LiteralPath $Path 
    $acl.SetAccessRule($accessRule) 
    Set-Acl -AclObject $acl -LiteralPath $Path 
} 

但是,請注意,Get-Acl無法在您的帳戶和您的某個組都不是所有者的情況下修改ACL。您可以通過使用icacls解決此問題:

[CmdletBinding()] 
Param(
    [Parameter(
    Mandatory=$true, 
    ValueFromPipeline=$true, 
    ValueFromPipelineByPropertyName=$true 
)] 
    [IO.FileSystemInfo]$Path 
) 

Begin { 
    $trustee = 'domain\user' 
    $permission = 'F' 
} 

Process { 
    & icacls $Path.FullName "/grant:r" "${trustee}:(CI)(OI)${permission}" | Out-Null 
} 
相關問題