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

我有一些想法:

但是我在这方面没有取得太大进展,我想知道你是否可以提供帮助。

谢谢,

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