powershellnullvariable-assignment

what does assignment to $null do in ($var=$null="...")


I saw in a script this kind of command:

Write-Verbose -Message ($var=$null="foo=$(<some computation>)")
<do something more with $var>

What is the point of assigning the string to $null before assigning to $var? I tried to remove this part and saw no difference. What am I missing?


Solution

  • What is the point of assigning the string to $null before assigning to $var?

    There is no point, because - in effect - the $null = assignment is ignored:


    [1] Note that, in PowerShell (Core) 7, a type constraint on a target variable can implicitly result in a conversion to that type, and it is that type's instance that is passed through, which can differ from the original input value; e.g. ([string] $var = 42).GetType().Name yields 'String'; ditto for chained assignments; e.g.
    $var2 = [string] $var1 = 42; $var2.GetType().Name also yields 'String'.
    By contrast, in Windows PowerShell (and now-obsolete PowerShell 7 versions up to v7.2.x), it is the original value that is passed through except if the target variable was previously created - irrespective of with what value and whether or not with a (potentially different) type constraint. This obscure distinction appears to be a bug;
    e.g., with no variable $var having yet been created, ([string] $var = 42).GetType().Name returns 'Int32', i.e. the input value was passed through as-is; by contrast,
    $var = $null; ([string] $var = 42).GetType().Name yields 'String', because the preexistence of $var causes the type constraint-based conversion to be applied. Note that this implies that simply executing ([string] $var = 42).GetType().Name twice yields 'Int32' on the first invocation, and 'String' on the second.