Blog Post

#PowershellBasics: Setting a variable vs a comparison.

,

In SQL Server both the set and equality functions are handled by the equals sign (=). For example:

Set

SET @var = 5;
SELECT @var = 5;

Equality

SELECT CASE WHEN @var = 5 THEN 'Equals' ELSE 'Not Equals' END;
IF @var = 5
PRINT 'Equals';
ELSE
PRINT 'Not Equals';

However, in some other languages that’s not how it works. In PowerShell for example the equals sign is always a set operation. In order to do a comparison you have to use -eq for equals or -ne for not equals. If you aren’t expecting it this can cause rather odd results

$var = 3
IF ($var = 5) {
    Write-Host "Equals"
} ELSE {
    Write-Host "Not Equals"
} 

I’ll bet you expect the output of that code snippit to be Not Equals right? It’s certainly what I was expecting the other day. But nope. It’s always going to be Equals. Why? If we change it slightly it becomes pretty obvious.

$var = 3
IF ($var = 5) {
    Write-Host $var
}

The result of this code snippit is 5. The reason is simple. Like I said above, the equals sign is always (at least to the best of my knowledge) a set operation. If we want to this to work correctly we have to use -eq.

$var = 3
IF ($var -eq 5) {
Write-Host "Equals"
} ELSE {
Write-Host "Not Equals"
}

If you want to look at other comparison operators for PowerShell you can look here.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating