使用 Get-ChildItem 时如何避免 UnathorizedAccessException?

Ste*_*man 5 powershell get-childitem

我正在使用 PowerShell 5.0 并编写一个脚本来递归地查找并列出当前目录下 log4net.dll 的所有版本。

Get-ChildItem log4net.dll -Recurse | % versioninfo | Export-Csv "C:\MyJunk\log4net.csv"
Run Code Online (Sandbox Code Playgroud)

上述语句开始按预期返回版本信息,但执行在我缺乏访问权限的第一个文件夹处停止:

Get-ChildItem : The specified network name is no longer available.
At line:1 char:1
+ Get-ChildItem log4net.dll -Recurse | % versioninfo | Export-Csv "C:\M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ReadError: (J:\ArcPlan_OracleWallet\Production:String) [Get-ChildItem], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

Get-ChildItem : Access is denied
At line:1 char:1
+ Get-ChildItem log4net.dll -Recurse | % versioninfo | Export-Csv "C:\M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand
Run Code Online (Sandbox Code Playgroud)

我以管理员身份运行 Windows PowerShell ISE。ExecutionPolicy 是 RemoteSigned,$ErrorActionPreference 是Continue。

理想情况下,我希望脚本能够询问每个文件夹的 ACL 并绕过我缺乏访问权限的所有文件夹(及其内容)。然而,另一种解决方案是绕过硬编码文件夹。作为 PowerShell 的新手,我关注的是后者。

我尝试绕过第一个问题文件夹(按名称),看看是否可以正常工作,但遇到相同的异常并且处理停止。

Get-ChildItem log4net.dll -Recurse | Where-Object { $_.FullName -notmatch '\\ArcPlan_OracleWallet\\?'} | export-csv 'C:\MyJunk\log4net.csv'
Run Code Online (Sandbox Code Playgroud)

谢谢。

sod*_*low 2

如果您想忽略错误,请使用-ErrorAction SilentlyContinue.

该参数还有其他有用的值,您可以在此处此处发现。

这是一个非常切题的好问题。

您还可以使用 获取有关此问题的帮助Get-Help about_CommonParameters

(您好,欢迎光临,如果您喜欢这个答案,请阅读本文^^)。