如何在Get-ChildObject的每个输出上运行脚本

时间:2015-05-26 13:54:26

标签: file powershell acl

创建脚本以递归方式更改整个目录上的ACL。简单脚本在一个文件上相应地更改ACL,但是我不知道如何在Get-ChildItem的每个文件上运行脚本

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,但我无法正确理解语法。

3 个答案:

答案 0 :(得分:1)

您可以在foreach循环中嵌入已有的代码。通过首先将Get-ChildItem调用的输出分配给变量来获取文件数组:

$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
}

答案 1 :(得分: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
}

答案 2 :(得分: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 $_
}

如果您想将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
}