Win10 Powershell – Simple If/Elseif Depends on Condition Order?

  • A+
Category:Languages

I'm attempting to write a deployment script that checks the OS major version, then runs command based on that. I can grab that just fine with [System.Environment]::OSVersion.Version.Major, but when I attempt to use that in an if/elseif statement, I always get the first condition, and somehow the variable changes.

So the code I'm working with to test is this (using a Windows 10 machine):

$OS_VERSION=$([System.Environment]::OSVersion.Version.Major)  if ($OS_VERSION = 6) {   Write-Output "OS Version is $OS_VERSION"   # Do stuff... } elseif ($OS_VERSION = 10) {   Write-Output "OS Version is $OS_VERSION"   # Do different stuff.. } 

I noticed that when I switch the order of the conditions it runs as expected, and even more frustrating, is that the statement works perfectly fine on a Windows 7 machine.

Is this a bug/quirk of Powershell I'm missing, or am I doing something stupid?

 


I thought I'd write this out since I can explain it better than my comment. When you enter an expression without assigning it, it gets output to the pipeline. In this case

$OS_VERSION = 6 

is an expression. If you wrap this in parentheses when entered at an interactive prompt, it'll output what the variable assigns at the same time as assigning the variable, much like 6 | Tee-Object -Variable OS_VERSION would, or a -PassThru switch on some cmdlets.

> ($Test = 6) >> 6 > $Test >> 6 

So what you're doing here is always assigning that variable to 6 which evaluates to true since if is truthy and non-zero is true. What you need is the -eq comparison operator.

More information can be found from the following command:

Get-Help -Name about_Comparison_Operators 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: