Windows PowerShell Tutorial 6 - Operators

Learn about the different kinds of Operators in PowerShell: How & When to use them



  1. Regedit32
    Before we get started, for those of you familiar with programming you probably already noted that the previous two Tutorials missed something that would be quite relevant both there, and also for the current Tutorial topic; that being 'Formatting' (i.e. Controlling how information is formatted and thus displayed in the Console or when written to an external file).

    I've done this intentionally, because I want to deal with that separately, after you have had the opportunity to learn the basics on dealing with an Objects data in PowerShell, which hopefully will make you realize that while very useful, it lacks a format style that might suit your personal tastes, or simply, make the Output easier to analyze or read.

    While it is not a massive topic to discuss, there are several features in the PowerShell Cmdlets worth breaking down, so I'll address that in the next Tutorial.

    Take a look at the following code:

    Code (PowerShell):
    Dir C:\Windows | Where { $_.length -gt 100000 }
    What do you think this is going to do?

    PS38.png
    Congratulations if you managed to work out what the above code would do!

    As you can see, Dir C:\Windows | Where { $_.length -gt 100000 } did the following:
    1. An Object was created from the Cmdlet Get-Children which we access here by using its Alias: Dir (i.e. Directory), which contained a Directory listing of the contents of C:\Windows
    2. This object was piped to become input for the Cmdlet Where-Object which was accessed via its Alias: Where.
    3. The Object was now passed through an expression which filtered the information contained inside this.object referenced by $_ using the method .length to check the objects size, and then a switch operator was used, that being -gt (i.e. Great than) to compare the size of this.object to 100000. This evaluation returns as either true or false.
    The end result is seen in the above image. Objects inside C:\Windows that are larger than 100,000 bytes and therefore true are displayed to the console. All other objects also located in C:\Windows return as false and are ignored and thus not displayed.​

    Challenge: Alter the code above to make use of advanced redirection to write the information both to the console and a text file on your Desktop. (I'll provide a solution at the end of this Article, but try doing it yourself without looking at the answer).

    PowerShell comes with a set of operators which allow you to create expressions you can use in your Statements to assign or filter data. In the above sample we used the switch operator -gt (Great than).

    An expression is simply a block of code which PowerShell uses to evaluate data in order for it to produce a result which can be returned to the Console, a variable, an external file, etcetera.

    As already stated the above sample code used an expression to return true or false and passed the true items to the Output stream which was written to the console.

    PowerShell includes a large variety of operators that you can use in your expressions and in this Tutorial we will be taking a look at several of these operators to introduce you to the concept of when and how to use them.

    PowerShell operators can be categorized into three groups:
    1. Comparison operators
    2. Logical operators
    3. Arithmetic operators
    The preceding code was an example of using a Comparison operator.
    • Nearly all operators are appended to a hyphen, for example: -gt.
      • The exceptions to this include one logical operator ! and the Arithmetic operators (e.g. +, -, *, /, %)
    • Operators are not case sensitive, so -gt or -GT will both work, however, generally when Scripting in PowerShell lowercase is used for operators.

    Comparison operators

    Comparison operators are used in PowerShell to compare the value on the left of the operator to the value on the right of the operator. A block of code using Comparison operators is generally referred to as an expression.

    There are a lot of Comparison operators to choose from; more than this Tutorial can possibly go through. Here is a sample of some of the Comparison operators most often used in Scripts:

    table2.png

    Note: PowerShell by default performs all comparison operations as a case-insensitive action, so the -ieq option is not really needed at all. That means a couple of things for you:

    1. You really only need to remember either the standard operator (for example -eq) or the Case-Sensitive operator (for example -ceq)
    2. If you are looking at code someone else wrote, it would be rare you'd see a Case-Insensitive operator being used (for example -ieq), but given some programmers like being formal, you now at least know what that -i before the operator means.
    To illustrate this take a look at the image below which shows an Array object that contains one instance of "dog", one "Cat", one "Dog", one "DOG" and one "Doggy"

    PS39.png



    Hopefully, this basic demonstration helps make it clearer to you the differences.

    Is that your 8 year old exclaiming that "Doggy" is a dog!

    Well true it is, so if you really wanted to include Doggy in the results of above examples, then this is when you'd use the -like comparator which allows you to use wildcards. Take a look at the image below, now using -like and *dog*

    PS40.png
    Using the wildcard with -like comparator we now correctly get 4 indexed positions in terms of there are 4 animals that are dogs in the array. Now if you happen to have a 4 year old insisting the Cat is a Dog -- ummm, LoL good luck! :rolleyes: Maybe try this to educate them:

    PS41.png

    OK so we've established a Cat is not a Dog. Hopefully, you also learned how to use all three methods of the -eq comparison operator, and also how you can use -like and -notcontains comparison operators. Time to try using these comparison operators with a Windows OS elated theme.

    Code (PowerShell):
    Get-Process | Where {$_.Responding -eq 'true' }
    What do you think the above piped statement couple with an expression using a comparison operator will do? Think about it for a moment, then simply type or copy & paste it into the Script pane in your Windows PowerShell ISE and click File > Run

    PS42.png


    The aforementioned code creates an object which contains all processes. This is piped to become input for the Where-Object cmdlet, which filters the input checking to see whether or not the process is responding. If it is responding a value of 'true' is returned and this process is listed to the console. If the process is not responding a value of 'false' will apply, and as a result that process will not appear on the console.

    That is achieved appending the Method .Responding to this.object and passing this through an expression that asks, does this.object equal true or false.

    What if you want to filter down the results even more though? Well that is where you can make use of wildcards. One of those wildcards is an asterisk * and if we modify are code a little like below we can filter the results to only include Microsoft processes, as opposed to a process for Firefox, Google Chrome, Norton Internet Security, etcetera:

    Code (PowerShell):
    Get-Process | Where {$_.company -like '*microsoft*'}
    PS43.png

    PowerShell has four wildcard choices as shown in the table below:

    table3.png

    As the wildcard * supports zero to any number of characters this allows you to find an item of interest regardless of its name. Here are two examples to demonstrate this:

    Example 1 — That dog is back!
    PS44.png

    Example 2 - Anything to do with Google
    PS45.png


    This second one obviously will not show much if you have not install a Google product on your machine. The thing to notice is the result in the Console. No mention of Google at all, but because we surrounded google with wildcard asterisks, and applied it to a Method comparing Company names with Processes, we were able to locate the Chrome entries as they are of course a Google product, that in this instance simply uses Chrome as the display name to the User.

    This search of course would also pick up Google processes like the Update tools it can install if you allow them to be installed and enabled. A handy way to locate those add-ons is using a simple script as above, which may help you locate and manually remove them if needed.

    Logical operators

    PowerShell offers four Logical Operators, which you can see in the table below:

    table4.png

    Logical operators allow you to connect more than one condition into a single expression. So far we have only used a single condition within an expression.

    So here are some examples of an expression using multiple conditions to illustrate how you use the logical operators in an expression.

    PS46.png
    If C:\Windows contains executable file and file is 200,000 KB or larger display it

    PS47.png
    If C:\Windows contains any executable files or any file type that is 200,000 KB or larger display it

    PS48.png

    Get processes with CPUs greater than 5 and not a Microsoft Corporation process

    PS49.png

    Get items from C:\ that are larger than 1KB and NOT a .ETL file.

    So you can see its very easy to use these logical operators and very helpful too given it helps to be able to filter out data you really do not want cluttering the screen.

    Arithmetic operators

    PowerShell allows you to use Arithmetic operators just a any programming language will. The table below illustrates this:

    table5.png

    There is nothing to earth shattering here, so I won't spend time showing this in action, other than to note you can use these operators with Strings too!

    PS50.png


    Well that concludes this tutorial. In the next tutorial I'll cover the aforementioned formatting of information written to the console or an external file (i.e. changing its default format).

    Solution to Challenge:

    PS51.png
    Well done if you worked this out on your own. You can delete the file you created on your Desktop at any time.


    Regards,

    Regedit32
    Ian likes this.