none
What does "if ($var1 -eq $null) {$var1 = (,$var2) }" mean? RRS feed

  • Question

  • I got the following code snipet from a script under the FIMAutomation section, and I was wondering if one of you guys could explain to me what is happening when the "if" is evaluated to null. In other words, what is the meaning of (,$ImportChange) and what is that actually doing?

    Is that how an empty/null array/list should be handled when the first element is added to it?

    if ($ImportObject.Changes -eq $null){             

        $ImportObject.Changes = (,$ImportChange)         

    } else {             

       $ImportObject.Changes += $ImportChange

    }

    Thursday, June 8, 2017 9:34 PM

Answers

  • Normally we would not write a script like this.

    This is how to write that code:

    $ImportObject.Changes += [array]$ImportChange

    This handles all cases by guaranteeing the result object is an array even if it is null to begin with.

    The result will always create or add to an array.  There is no need for a lot of odd code.  The writer of the code was not a programmer and had limited experience with PowerShell.

    The purpose of the code was to guarantee that an array was being created as a direct assignment would always over write and += would concatenate an not add if the property was null to begin with.


    \_(ツ)_/

    Thursday, June 8, 2017 10:14 PM

All replies

  • Normally we would not write a script like this.

    This is how to write that code:

    $ImportObject.Changes += [array]$ImportChange

    This handles all cases by guaranteeing the result object is an array even if it is null to begin with.

    The result will always create or add to an array.  There is no need for a lot of odd code.  The writer of the code was not a programmer and had limited experience with PowerShell.

    The purpose of the code was to guarantee that an array was being created as a direct assignment would always over write and += would concatenate an not add if the property was null to begin with.


    \_(ツ)_/

    Thursday, June 8, 2017 10:14 PM
  • Thank you for the clarification! I will use your recommended syntax which is a lot clearer and more intuitive.
    Friday, June 9, 2017 1:36 PM