我遇到了一个奇怪的情况,我无法弄清楚问题。我希望获得给定路径的所有子目录的ACL和AccessRules。如果我单独进行,我不会有任何错误
gci -recurse | Where-Object { $_.PSIsContainer } | Get-Acl | Format-List | Out-File C:\temp\permission.txt
gci -recurse | Where-Object { $_.PSIsContainer } | Get-Acl | foreach {$_.GetAccessRules($true, $true, [System.Security.Principal.NTAccount])} | Out-File C:\temp\permission1.txt -Append
但是,我想在foreach循环中执行此操作,以更好地操作和处理文件的生成方式。这是我在剧本中尝试做的事情:
sl c:\test_folder
gci * -Recurse | Export-Csv c:\temp\dir.csv -Force
$pastas = gci -Recurse | where {$_.PsIsContainer}
if (Test-Path C:\temp\permission.txt)
{
ri c:\temp\permission.txt
}
foreach ($pasta in $pastas)
{
$pasta
Test-Path $pasta
$acl = get-acl $pasta
$acl | format-list | Out-File -FilePath c:\temp\permission1.txt -Append
$acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) | Out-File -FilePath c:\temp\permission1.txt -Append
}
当我在foreach
变量的根目录中直接处理$pastas
个文件夹时,Test-Path
会返回true
。但是,在第一个子目录中,Test-Path
返回false
,但该文件夹确实存在。在get-acl上,我得到了PathNotFound异常:
Get-Acl : Não é possível localizar o caminho 'Exportacao' porque ele não existe.
Em C:\Temp\Script Get Info.ps1:12 caractere:17
+ $acl = get-acl <<<< $pasta
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId : GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
我做错了什么?
答案 0 :(得分:2)
尝试:
Test-Path $pasta.fullname
$acl = get-acl $pasta.fullname
答案 1 :(得分:2)
sl c:\test_folder
gci * -Recurse | Export-Csv c:\temp\dir.csv -Force
$pastas = gci -Recurse | where {$_.PsIsContainer}
if (Test-Path C:\temp\permission.txt)
{
ri c:\temp\permission.txt
}
foreach ($pasta in $pastas)
{
$pasta.FullName
Test-Path $pasta.FullName
$acl = get-acl $pasta.FullName
$acl | format-list | Out-File -FilePath c:\temp\permission1.txt -Append
$acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) | Out-File - FilePath c:\temp\permission1.txt -Append
}
尝试上面的脚本。
你的代码失败的原因是因为$ pasta是一个FileInfo对象,而Test-Path需要一个带有完整路径的字符串。