4oo4
4oo4

Reputation: 295

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

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?

Upvotes: 3

Views: 857

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

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

if ($OS_VERSION = 6) {

is an expression (since the if statement evaluates expressions for a boolean value to take action). 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:

if ($OS_VERSION -eq 6) {

More information can be found from the following command:

Get-Help -Name about_Comparison_Operators

Upvotes: 11

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

PowerShell does not use = as a comparison operator.

If you want to compare for equality, the operator is -eq:

if ($OS_VERSION -eq 6) {
  Write-Output "OS Version is $OS_VERSION"
  # Do stuff...
} elseif ($OS_VERSION -eq 10) {
  Write-Output "OS Version is $OS_VERSION"
  # Do different stuff..
}

This will correct your problem. You should take a close look at Get-Help -Name about_Comparison_Operators (or read the link).

Upvotes: 5

Related Questions