The calculated properties do not throw an exception in Powershell. What are the workarounds?

Apparently, there is a quirk design in Powershell that prevents exceptions that are thrown inside the Calculated property Expression from bubbles up. All that happens is the value of the Settlement property ending in zero.

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 Get-KBValue an exception, then the value of the Get-KBValue property is set to $null , and the script continues.

Possible workarounds:

  • Use try/catch{break} in the expression (CC recommended)
  • Verify later. Although this can be complicated by the fact that $null can be valid in some cases.
  • Use a custom object instead of a computed property. But it is not so nice.

Any thoughts?

+3
source share
1 answer

Using try / cacth expression in expression can help you?

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

All Articles