我不明白陷阱是如何工作的

时间:2016-12-11 23:20:24

标签: powershell powershell-trap

我正在尝试创建一个陷阱命令,用于捕获未找到文件的异常。这是代码:

Trap {
  Clear-Host
  Write-Host "The file you are looking for does not exist"
}

Get-ItemProperty C:\fake

我是否误解了如何做到这一点?

1 个答案:

答案 0 :(得分:4)

陷阱仅在终止错误(停止管道的错误)时执行,因此首先您需要更改有问题的cmdlet的ErrorAction行为:

Trap {
  Clear-Host
  Write-Host "The file you are looking for does not exist"
}

Get-ItemProperty C:\fake -ErrorAction Stop

要抑制错误记录随后冒泡到调用者,请从陷阱内部返回当前范围:

Trap {
  Clear-Host
  Write-Host "The file you are looking for does not exist"
  return
}

Get-ItemProperty C:\fake -ErrorAction Stop

为了不必一直明确指定-ErrorAction Stop参数参数,在脚本/函数的开头设置$ErrorActionPreference变量:

$ErrorActionPreference = 'Stop'

或使用$PSDefaultParameterValues哈希表为特定cmdlet设置它:

$PSDefaultParameterValues['Get-ItemProperty:ErrorAction'] = 'Stop'
$PSDefaultParameterValues['Do-OtherStuff:ErrorAction'] = 'Stop'
$PSDefaultParameterValues['Set-*:ErrorAction'] = 'Stop'