Powershell Comparators Cheatsheet

I've used powershell quite a lot, I find it most useful at work when setting up build pipelines for team city, its really handy when creating build steps and you need team city to execute some custom functionality e.g. specrun. It's also good when trying to do some analysis on particular installed nuget packages. There are many uses, but these are main uses.

I find the syntax quite easy, I occasionally get caught out with projections, filtering and iterating, so I thought I'd write a quite cheat sheet post that may help others out there!

Comparison Operators:

-eq Equal

-ne Not Equal

-gt Greater Than

-lt Less Than

-le Less Than or Equal

-ge Greater Than or Equal

*Powershell is case insensitive so for case comparison you must precede the operator with c.
An example of this is

*Powershell also does not care that the type matches, for example it will try and convert an integer within a string into an integer before comparison. An example of this is

Powershell also has the ability to compare collections and types without having to reference any external modules. Here are some more examples:

-contains -notcontains Checks a collection of elements for a specific element

-in -notin Checks whether a collection contains a specific element

-like -notlike Used for string wildcard comparison

-match Used for regex matching

We should next look at boolean operations, which can be combined with any of the above to create more complex statements

-and Both comparisons must be equal to return true

-or At least one of the comparisons must be equal to return true

-not Negates the comparison

-xor Exclusive or returns true if one part of the expression is true, but false if both are true

Knowing all the theory of this is fine, I guess what you want to see is some real world examples. I have provided some below.
In my next post I'll be creating a cheatsheet for Selectors, Filters and Iterators, which in my opinion is much more interesting!

Some real world examples:

Gets all the powershell commands that contain the word "Process"

Gets all the processes, where the process name matches svchost

Get all the directories where the name matches either "Desktop" or "Documents"


0 mentions:

Post a Comment