在 PowerShell 中捕获 UnauthorizedAccessError
Catching UnauthorizedAccessError in PowerShell
我想找到指定目录中的所有文件并存储任何 folders/files 抛出访问被拒绝错误(如下所示)的完整路径。
Get-ChildItem : Access to the path 'C:\ProgramData\Microsoft\Crypto\SystemKeys' is denied.
At line:1 char:1
+ Get-ChildItem "C:\ProgramData\Microsoft\Crypto\SystemKeys"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\ProgramData\...ypto\SystemKeys:String) [Get-ChildItem], Unauthoriz
edAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
我使用的命令是:
$Allfiles = Get-ChildItem -Path $Directories -Recurse -Force -File | % { $_.FullName }
我有一些想法:
- 正在为
DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand exceptions
解析 $error
变量
- 使用参数
-ErrorVariable
和 -ErrorAction
- 使用
try{} catch{}
- 使用 $_
但是我在这方面没有取得太大进展,我想知道你是否可以提供帮助。
谢谢,
TheCube
# Use -ErrorVariable errs to collect all errors in variable $errs.
# -ErrorAction SilentlyContinue silences display output of the errors.
$allfiles = Get-ChildItem -Path $Directories -Recurse -Force -File -ErrorVariable errs -ErrorAction SilentlyContinue
# List all paths that resulted in an unauthorized-access exception.
# Note: Given that other errors are unlikely to occur, you could omit the
# `where` call.
$errs | where { $_.Exception -is [UnauthorizedAccessException] } |
select -ExpandProperty TargetObject
我想找到指定目录中的所有文件并存储任何 folders/files 抛出访问被拒绝错误(如下所示)的完整路径。
Get-ChildItem : Access to the path 'C:\ProgramData\Microsoft\Crypto\SystemKeys' is denied.
At line:1 char:1
+ Get-ChildItem "C:\ProgramData\Microsoft\Crypto\SystemKeys"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\ProgramData\...ypto\SystemKeys:String) [Get-ChildItem], Unauthoriz
edAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
我使用的命令是:
$Allfiles = Get-ChildItem -Path $Directories -Recurse -Force -File | % { $_.FullName }
我有一些想法:
- 正在为
DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand exceptions
解析 - 使用参数
-ErrorVariable
和-ErrorAction
- 使用
try{} catch{}
- 使用 $_
$error
变量
但是我在这方面没有取得太大进展,我想知道你是否可以提供帮助。
谢谢,
TheCube
# Use -ErrorVariable errs to collect all errors in variable $errs.
# -ErrorAction SilentlyContinue silences display output of the errors.
$allfiles = Get-ChildItem -Path $Directories -Recurse -Force -File -ErrorVariable errs -ErrorAction SilentlyContinue
# List all paths that resulted in an unauthorized-access exception.
# Note: Given that other errors are unlikely to occur, you could omit the
# `where` call.
$errs | where { $_.Exception -is [UnauthorizedAccessException] } |
select -ExpandProperty TargetObject