Calculated properties do not throw exceptions in Powershell. What are the workaround possibilities?

风格不统一 提交于 2019-12-10 10:04:06

问题


Apparently there is a by design quirk in Powershell that prevents exceptions that are thrown inside a Calculated Property Expression from bubbling up. All that happens is the value of the Calculated Property ends up being 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 }}

If the Get-KBValue function throws an exception then the value of the Kbytes property is set to $null and the script continues.

Possible workarounds:

  • Use try/catch{break} within the Expression (Suggested by @C.B.)
  • Validate afterwards. Although this might be complicated by the fact that $null could be valid in some cases.
  • Use a custom object instead of a calculated property. But this is not as nice.

Any thoughts?


回答1:


Use a try/cacth in expression can help you?

10..0 | SELECT @{n="Value";e={ try { 10/$_ } catch { "error: $_" }}}


来源:https://stackoverflow.com/questions/16482316/calculated-properties-do-not-throw-exceptions-in-powershell-what-are-the-workar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!