我有一个审核NTFS权限的脚本。
ForEach ($Folder in $Folders){
$ACLs = Get-ACL $Folder.FullName | % { $_.Access }
ForEach ($ACL in $ACLs){
$OutInfo = $Folder.Fullname + "," + $ACL.IdentityReference + "," + $ACL.AccessControlType + "," + $ACL.FileSystemRights + "," + $ACL.IsInherited + "," + $ACL.InheritanceFlags + "," + $ACL.PropagationFlags
Add-Content -Value $OutInfo -Path $outputCSV
}
}
但是,由于脚本作为用户的上下文运行,因此帐户无权访问某些文件夹,因此在powershell CLI中将错误吐出来,说访问被拒绝等。我该怎么做:
a). Hide it from the Powershell CLI
b). Redirect it to a notepad/txt file log so I still have the information.
+ $Folders = dir $pathToFolders -recurse | where {$_.psiscontainer -eq $true}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (F:\SEPM:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ACL : Attempted to perform an unauthorized operation.
使用以下方法不会将其写入文本文件?
答案 0 :(得分:2)
要重定向错误流,请使用2> filename
语法(或2>> filename
附加)。
为了演示,让我们使用这个功能:
Function Test {
Write-Error "Written to stderr"
Write-Output "Written to stdout"
}
然后你可以调用Test 2> stderr.log
将“写入stderr”写入文件stderr.log。您仍然可以重定向stdout,Test 2> stderr.log > stdout.log
会将“写入stderr”写入stderr.log,将“写入stdout”写入stdout.log。
修改强> 在管道中执行此操作时,请确保在写入错误的管道部分中执行重定向。也就是说,
$Folders = dir $pathToFolders -recurse 2> stderr.log | where {$_.psiscontainer -eq $true}
,
不是
$Folders = dir $pathToFolders -recurse | where {$_.psiscontainer -eq $true} 2> stderr.log
请注意,这意味着您可以实际将错误从不同的命令重定向到不同的错误日志,如果您愿意,$Folders = dir $pathToFolders -recurse 2> dir.err | where {$_.psiscontainer -eq $true} 2> where.err