Search code examples
powershellnull-conditional-operator

Null Conditional in Powershell?


C# and other languages have null-conditionals usually ?.

A?.B?.Do($C);

Will not error out when A or B are null. How do I achieve something similar in powershell, what's a nicer way to do:

if ($A) {
  if ($B) {
    $A.B.Do($C);
  }
}

Solution

  • PowerShell doesn't have the null-conditional operator, but it silently ignores property references on null-value expressions, so you can just "skip" to the method call at the end of the chain:

    if($null -ne $A.B){
      $A.B.Do($C)
    }
    

    Works at any depth:

    if($null -ne ($target = $A.B.C.D.E)){
        $target.Do($C)
    }