#PowershellBasics: Setting a variable vs a comparison.

1

April 27, 2021 by Kenneth Fisher

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.

One thought on “#PowershellBasics: Setting a variable vs a comparison.

  1. […] Kenneth Fisher avoids overloading: […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,548 other followers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: