【问题标题】:Can PowerShell trap errors in GetChildItem and continue looping?PowerShell 可以捕获 GetChildItem 中的错误并继续循环吗?
【发布时间】:2011-10-20 01:00:18
【问题描述】:

我有一个 PowerShell 脚本,它在 for 循环中使用 GetChildItem 向下递归文件系统。随着它的移动,它正在修复它发现的 ACL 问题(主要是有人阻止了 BUILTIN\Administrators 帐户)......但是有些它自己无法处理,比如当我得到 [System.UnauthorizedAccessException] 如果有是一个明确的“拒绝”ACE。

这行代码如下所示:

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction Continue) {
    ...
}

当它偶然发现无法读取的路径时,它会给出以下异常:

Get-ChildItem:对路径“C:\TEMP\denied”的访问被拒绝。在 修复 ACLs.ps1:52 字符:31 + foreach($file in Get-ChildItem

我想尝试/捕获或捕获错误,以便我可以就地修复 ACL(即删除“拒绝”),并且 - 最重要的是 - 继续循环而不会失去我的位置。对我有什么建议吗?

【问题讨论】:

  • 给出一些你正在使用的代码

标签: powershell try-catch acl


【解决方案1】:

你用过静默继续吗?

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction silentlycontinue) {
    ...
}

【讨论】:

  • 确实我有......但它仍然在代码块中运行,并出现更多错误。由于traptry/catch 通常适用于“停止”错误,因此到目前为止我发现的最佳选择是按照您的建议使用-ErrorAction SilentlyContinue,然后在代码块的第一行检查我们是否if ($error) {... 出现错误。
【解决方案2】:

询问怎么样?

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction Inquire) {
...
}

可能会打开第二个 PS 窗口来解决错误,然后通过选择 Y 继续在第一个 PS 窗口中继续执行命令。

你也可以使用 ErrorVariable

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorVariable a) {
...
}

Get-Variable a 或 $a 将显示该命令导致的所有错误。您还可以使用 +variablename (+a) 将错误添加到现有变量。

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorVariable +a) {
...
}

【讨论】:

  • 好主意,@Jesse。谢谢!
  • 致所有人:不要犯我在尝试这个时犯的同样错误。不要在 -ErrorVariable 行上为变量添加 $。一件容易被忽视的事情,在我发现那个错字之前我会认为这不起作用。
【解决方案3】:

我会用它来:

ForEach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction silentlycontinue) {
    ...
}

然后,您可以过滤 $Error 以获取具体的 Permission Denied 类型错误:

$permError += $Error | Where-Object { $_.CategoryInfo.Category -eq 'PermissionDenied' }

ForEach($deniedAccess in $permError)
{
    $deniedAccess.CategoryInfo.TargetName | Do Stuff
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多