计算属性不会在Powershell中抛出异常.有哪些可行的解决方案?

And*_*age 3 powershell exception-handling

显然,Powershell中存在一个设计怪癖,它可以防止计算属性表达式中抛出的异常冒泡.所有发生的事情是计算属性的值最终为null.

function Get-KBValue() {
    # Some Logic here that can throw an exception
}

....

Get-ChildItem C:\Test | 
    Select-Object Name, CreationTime,  @{Name="Kbytes"; Expression={ Get-KBValue }}
Run Code Online (Sandbox Code Playgroud)

如果Get-KBValue函数抛出异常,则将Kbytes属性的值设置为$null,脚本将继续.

可能的解决方法:

  • try/catch{break}在表达式中使用(由@CB推荐)
  • 之后验证.虽然$null在某些情况下这可能是有效的,但这可能会很复杂.
  • 使用自定义对象而不是计算属性.但这不是那么好.

有什么想法吗?

CB.*_*CB. 5

在表达式中使用try/cacth可以帮到你吗?

10..0 | SELECT @{n="Value";e={ try { 10/$_ } catch { "error: $_" }}}
Run Code Online (Sandbox Code Playgroud)