PowerShell for Windows Admins

Jul 5 2018   10:43AM GMT

PowerShell not equal

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

The Powershell not equal operator is –ne. This how you use it.

When dealing with numbers:

PS> $a = 3
PS> $b = 5
PS> $a -ne $b
True

When dealing with strings you have a bit more choice:

PS> $a = ‘abcd’
PS> $b = ‘efgh’
PS> $a -ne $b
True

By default PowerShell is case insensitive so

PS> $a = ‘abcd’
PS> $b = ‘ABCD’
PS> $a -ne $b
False

If the only difference is case then –ne reports they are the same.

If you need a case insensitive test use –cne

PS> $a = ‘abcd’
PS> $b = ‘ABCD’
PS> $a -cne $b
True

Because there are case differences the strings are different so you get a result of True

If you need a case insensitive test use –ine so you know you’re ignoring case

PS> $a = ‘abcd’
PS> $b = ‘ABCD’
PS> $a -ine $b
False

The major problem with use not equal is that you’re in double negative

if X –ne Y then it means they are the same if the result is false

PS> $a = 3
PS> $b = 3
PS> $a -ne $b
False

Its always easier to comprehend a test for equality rather than inequality especially if you’re nesting tests.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: