Powershell使用SilentlyContinue捕获非终止错误

HiT*_*ech 4 powershell powershell-2.0 powergui powershell-3.0

我想捕获并处理非终止错误,但使用-ErrorAction SilentlyContiune.我知道我需要使用-ErrorAction Stop来捕获非终止错误.该方法的问题在于我不希望try脚本块中的代码实际停止.我希望它继续但处理非终止错误.我也希望它保持沉默.这可能吗?也许我会以错误的方式解决这个问题.

我想要处理的非终止错误的一个示例是来自Get-Childitem的关键字文件夹的访问被拒绝错误.这是一个例子.

$getPST = Get-ChildItem C:\ -Recurse -File -Filter "*.PST" 
$pstSize = @()
Foreach ($pst in $getPST)
{
     If((Get-Acl $pst.FullName).Owner -like "*$ENV:USERNAME")
     {
         $pstSum = $pst | Measure-Object -Property Length -Sum      
         $size = "{0:N2}" -f ($pstSum.Sum / 1Kb)
         $pstSize += $size
     }
}
$totalSize = "{0:N2}" -f (($pstSize | Measure-Object -Sum).Sum / 1Kb)
Run Code Online (Sandbox Code Playgroud)

mjo*_*nor 5

你不能使用带有ErrorAction SilentlyContinue的Try/Catch.如果要静默处理错误,请使用Stop作为ErrorAction,然后在Catch块中使用Continue关键字,这将使其继续循环使用下一个输入对象:

$getPST = Get-ChildItem C:\ -Recurse -File -Filter "*.PST" 
$pstSize = @()
Foreach ($pst in $getPST)
{
 Try {
      If((Get-Acl $pst.FullName -ErrorAction Stop).Owner -like "*$ENV:USERNAME")
       {
        $pstSum = $pst | Measure-Object -Property Length -Sum      
        $size = "{0:N2}" -f ($pstSum.Sum / 1Kb)
        $pstSize += $size
       }
     }

 Catch {Continue}
}
$totalSize = "{0:N2}" -f (($pstSize | Measure-Object -Sum).Sum / 1Kb)
Run Code Online (Sandbox Code Playgroud)

  • 你不能打断get-childitem.您可以将错误操作设置为静默继续,并使用错误变量收集错误并在完成后处理它们. (2认同)