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