Assignments in PowerShell If Statements

You probably learned early on in your PowerShell experience that -eq and = were very different things.

I still occasionally write

if($x=5)

when I mean to write

if($x -eq 5)

The first will always evaluate to $true, which is generally not what you want.

One trick I’ve seen before is to put the constant (if there is one) on the left-hand side, which causes the assignment to fail with an error, alerting you to the fact that you did something wrong:

if(5 -eq $x)
or 
if(5=$x)

I don’t know if I would be able to even type the second without seeing the problem. Anyway, the point of this post isn’t that you shouldn’t use = in an if statement, but a useful situation where you might consider using it.

As a scenario, consider looking for services that are set to automatically start, but are currently stopped. I know I’ve done that before. What if you wanted to write the list of services meeting that criteria to a log file, but only if there were some that matched.

You might do something like this:

$services=get-ciminstance win32_service -filter "StartMode='Automatic' and State='Stopped'"
if($services){
   $Services | out-csv c:\temp\StoppedServices.csv
}

Putting the assignment in the if statement saves you a line:

if($services=get-ciminstance win32_service -filter "StartMode='Automatic' and State='Stopped'"){
   $Services | out-csv c:\temp\StoppedServices.csv
}

The value of the assignment statement is the value of the right-hand side. If there aren’t any services, the condition is false and we don’t try to write an empty file.

This isn’t a world-changer, but it might come in handy.

What do you think?

–Mike

6 Comments

  1. I often use this construct myself, although I occasionally feel a little uneasy about it…

    I guess a good alternative is to disambiguate the assignment by adding an explicit conditional check:
    If (($services=Get-Services) -ne $Null) {…}

    (Although I personally tend not to do this (possibly due to my C programming background from years’ ago!!))

    Cheers,
    Chris

  2. > The first will always evaluate to $true, which is generally not what you want.

    It will evaluate to whatever is in the variable following the assignment.

    if($x = $false) { ‘Never gonna happen’ }

    • Good point. I guess I wasn’t clear. Most of the time we aren’t assigning null. $False, on the other hand is a bit more likely.

Comments are closed.