【发布时间】:2019-10-25 12:29:29
【问题描述】:
Try-catch 似乎无法可靠地捕获所有错误。 get-ChildItem 上的 Try-catch 不会报告在 try-catch 之外报告的所有访问错误。
编辑:try-catch 不可靠是不正确的,它只报告一个错误是有充分理由的。请参阅我对已接受答案的评论,了解我对这个问题的误解。
在运行 PowerShell 5.1 的 Windows 10 Pro 64 中,此脚本:
$sScriptName = "ErrorTest.ps1"
write-host ("I will get the file structure of ""C:\Windows\System32"", but this yields two access-denied errors:")
$aoFileSystem = @(get-ChildItem "C:\Windows\System32" -recurse -force)
write-host ("I will now do it again and trap for those errors. But I only get one of them:")
try {$aoFileSystem = @(get-ChildItem $sPath -recurse -force -ErrorAction Stop)}
catch [System.UnauthorizedAccessException]
{$sErrorMessage = $_.ToString()
write-host ("System.UnauthorizedAccessException: " + $sErrorMessage.substring(20, $sErrorMessage.length - 32))}
以管理员身份在 ISE 中运行,得到以下输出:
PS C:\WINDOWS\system32> D:\<path>\ErrorTest.ps1
I will get the file structure of "C:\Windows\System32", but this yields two access-denied errors:
get-ChildItem : Access to the path 'C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache\Content.IE5' is denied.
At D:\<path>\ErrorTest.ps1:5 char:19
+ ... aoFileSystem = @(get-ChildItem "C:\Windows\System32" -recurse -force)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\Windows\Syst...che\Content.IE5:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
get-ChildItem : Access to the path 'C:\Windows\System32\LogFiles\WMI\RtBackup' is denied.
At D:\<path>\ErrorTest.ps1:5 char:19
+ ... aoFileSystem = @(get-ChildItem "C:\Windows\System32" -recurse -force)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\Windows\Syst...es\WMI\RtBackup:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
I will now do it again and trap for those errors. But I only get one of them:
System.UnauthorizedAccessException: C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache\Content.IE5
PS C:\WINDOWS\system32>
我想记录访问错误,但是当我尝试捕获它们时,我只得到第一个。当我诱捕他们时,我需要做什么才能让第二个出现?
编辑:我收到一条消息,告诉我我需要编辑我的问题以解释它与Can PowerShell trap errors in GetChildItem and continue looping? 的不同之处。因此,我将在此重复我在回应 Scepticalist 下面的评论时所说的话。这个问题是针对get-ChildItem 在ForEach 循环中的。我的问题不涉及这样的循环。尽管如此,我还是从那里接受的答案中尝试了一些东西,使用-ErrorAction SilentlyContinue,但这隐藏了错误而不捕获它们。但是,在我找到并即将发布的解决方案中,我确实将-ErrorAction SilentlyContinue 与-ErrorVariable 结合使用。
【问题讨论】:
-
这里已经回答了这个问题:stackoverflow.com/questions/6942747/…
-
@Sceptalist :不,我看过了。那是在
ForEach循环中的get-ChildItem。我的问题不涉及这样的循环。尽管如此,我还是在那里尝试了接受的答案,即使用-ErrorAction SilentlyContinue,这只会隐藏错误,不会捕获它们。 -
那么我怀疑做你需要的唯一方法是在你去的时候构建一个新数组,标记被拒绝的文件。
-
那为什么还要使用 try-catch 呢?只需使用
$error变量即可捕获相同的数据。