Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Set-Variable doesn't overwrite a variable when an empty list passed through pipe

Context:

  • You can set a value to variable with Set-Variable.
> "foo" | Set-Variable var
> $var
foo
  • You can also overwrite a value of variable like this:
> "foo" | Set-Variable var
> $null | Set-Variable var
> $var

Problem:

  • The value of variable is not overwittern when you pass empty list to Set-Variable like this:
> "foo" | Set-Variable var
> @() | Set-Variable var
> $var
foo
  • This problem often arise when you parse empty JSON and store the result to a variable.

Reason:

  • This behavior is by design in PowerShell 4.0.
  • This problem is not occurred in PowerShell 2.0 (bundled with Windows 7). You can run PowerShell in v2.0 mode by using -version 2 option (in Windows environment), but this behavior will not changed with this option. Cmdlets in latter of the pipeline will not be executed if there is no object passed to the pipe. (The list will be split into entries and passed to the pipe, and there is no entries in the list)

Added 2017-04-12

The problem can be reproduced in PowerShell 2.0.

Solution:

You should use an assignment statement instead of Set-Variable if the result of Cmdlet could be an empty list.

Note:

  • Tee-Object has same problem.