Development Powershell Tutorials

PowerShell – What’s your type

It can be hard knowing what your type is but lets try to figure it out in this PowerShell tutorial about TYPES.

You can actually get pretty far with PowerShell without having to think much about types but it is handy to know a bit about them and how to utilize their properties and methods to improve your scripts.

Since PowerShell is very good at guessing the type we don’t always have to define it, but we can do so by prefixing the variable with the type name enclosed in square brackets.

We’ll begin with looking at some of the most common types that you most likely have already used, maybe without knowing the difference.


Integer (INT) comes in a few different sizes depending on how large a number you need stored.
A integer can only store numbers and nothing else.
When assigning a integer variable with a value, you do not use quotation marks.

# 64 bit integer


# Default integer which is 32 bit, [int32]


# 16 bit integer


# Assigning a variable with a integer value
$myInt = 1337


Next up is string which is text and yes the text can contain numbers πŸ˜‰

# Assign a string value to a variable
$myString = "Henlo fren, am string!!1!!1!"

# Use Read-Host to assign a string value to a variable
$name = Read-Host "Please enter your name"

Arrays of a type

We can also let PowerShell know that we want an array of a specific type, which mean a collection of something. Lets look at some examples.

[string[]]$stringsThatStings = "Bees","Wasps","Needles","TheTruth"

[int[]]$numbersForPlumbers = 85,86, 88, 88, 89, 90, 92, 95, 96, 02, 06, 07, 09, 10, 11, 12, 12, 13, 15, 16, 17, 19, 21

We still use the type definition [string] but now we also add an empty square bracket set, [string[]].
To seperate the values we use comma between them.

# These two values are different types, one is a int, the other a string
"1337" # string
1337 # int

# Addition differences between string and integer
"1337" + 3 # 13373

1337 + 3 # 1340

"1337" -as [int] # Also returns an int, but does not throw an error if the string can't be converted

Type Methods

These types also provides us with tools to work with them called methods.
We can call these methods from an object of that type or by using the type definition.
Lets jump into the examples and take a better look at this.

# String formatting
$car = "Corvette C06"
$message = "Did you see the {0} that just drove by?"

# But I prefer this
"Did you see the $car that just drove by?"

# You can also do
"Did you see the " + $car + " that just drove by?"

# Lets use the stingy stringy again
[string[]]$stringsThatStings = "Bees","Wasps","Needles","TheTruth"

# Now we'll use the Join() method with two arguments, the first is what we want to add between the strings. 
# The second argument is our string array (stingray for short?)
[string]::Join(", ",$stringsThatStings)

# Converts the string representation of a number to an int
[int]::Parse("1337") # This returns an int

[int]::Parse("leet 1337") # This fails, the string to be parsed can only contain numbers "Input string was not in a correct format."
# As a side note, you could use regex to make sure that you only parse numbers
[int]::Parse(("leet 1337" -replace "[^0-9]","")) 
# Basically, replace everything that is NOT a number

First we have a couple of pretty self explanatory examples of building strings that contain variables.
When you add a variable in a string, the value of the variable will be displayed when the code is executed.

Next up is an example of how we can take an array of strings and merging them whilst adding something between them (called a delimiter).
In this example it just a simple comma and space, but it could be anything really, you could write something like: [string]::Join(” = sharp and can hurt a lot. “,$stringsThatStings)

Last example shows the parse method from the integer type which can convert a string representation of a integer to an actual integer.

Something I use quite a lot is checking if a string variable is empty. You might think it would be sufficient to just do If($myString -eq “”) but that will fail from time to time.
Best way I’ve found is to use if([string]::IsNullOrWhiteSpace($myString)).

# Type methods
[string[]]$ideas = "Waffle Truck made of waffles",""," ","Code that works the first time","   "

foreach($idea in $ideas){
        Write-Host "You should think a bit more about the idea '$idea'"
        Write-Host "Your idea '$idea' might just work, go for it!"


This type is used for, you guessed it – transporting wheat to… No wait, I meant dates and time!

Psst! Dont forget to follow along with the examples, and if you type them yourself it’ll be easier to remember!

[datetime]::DaysInMonth(2022,11) # Year, month

# Lets LEAP into some more examples
2000..2022 | foreach{ if([datetime]::DaysInMonth($_, 2) -gt 28){ "$_ was a leap year" } }

[int]$yourBirthYear = Read-Host "Enter your birth year as an int"
if([datetime]::DaysInMonth($yourBirthYear,2) -eq 29){ 
    "You were born during a leap year" 
    "You were not born during a leap year" 

# Lets improve it
    "You were born during a leap year" 
    "You were not born during a leap year"

# Two ways of getting the current date
# Or

$rubbishDateFormat = "Month10:Day5:Year2022"
[datetime]::ParseExact($rubbishDateFormat,"'Month'MM':Day'd':Year'yyyy",$null) | Get-Date -Format "yyyy-MM-dd" # We use both double qoutes (") and single qoutes (') in order to specify what is just a string, and what is the actual data 
# More about time, dates and what the formats mean:


These fellas are simple, they are either true or false.

[bool]$isPowerShellAwesome = $true

# IF our boolean is true
    "PowerShell is awesome, you are totally right!"
# Else if the boolean is false
    "Sorry but you are wrong, PowerShell is awesome!"
    $isPowerShellAwesome = $true # ;)


# You will encounter switches when running normal cmdlets 
Stop-Process Notepad -WhatIf 
# You do not need to add any value to a switch. If you use the switch then it use set to $true, else it is $false

# But quite often you'll encounter switches which has been implemented with $true as a default value, and if you just pass the switch again it wont remove that. 
# In order to remove a switch that has default value set to $true, pass the switch with a colon directly after followed by the static variable $false
Stop-Process Notepad -Confirm:$false 

function Write-Stuff{
        $Text = $Text.ToUpper()

    Write-Host $Text

Write-Stuff "PowerShell rocks!" -Yell

Still loads of things to learn about types and how to best utilize them

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Powershell Tutorials

PowerShell – Been stuck on loops FOR a WHILE

Yeah… I had to make that pun!

Ok so we are still spinning around the subject of loops in Powershell. This time as you might suspect we’re going to take a look at For and While.

Now I don’t typically use these but figured we’d talk a bit about them so that I have a legitimate reason for that pun πŸ˜‰

For loop

for ($i = 0; $i -lt 4; $i++){ 
    Start-Process Notepad

Above is a simple For loop that will start Notepad. Can you guess how many Notepads will be opened?

The condition (the part between the parentheses) has three parts separated by semicolons.

In the first part we specify a variable and assign a number to it, in this case 0.
Next we decide for how long the loop should run, I choose to continue looping as long as $i is less than 4.
Last part is making sure that the value of $i changes so that the loop eventually stops. I used $i++, which means that $i will increase by 1 each cycle.

Besides starting Notepad a bunch of times we also return the value of $i, returned values from the example:

While loop

$i = 0

while($i -le 4){
    Start-Process notepad


In this While loop example we are again using $i with an initial value of 0, but it has to be specified outside of the While statement.
You can read the code simply as “while (this is true) {do this}”.

Instead of -lt (less than) we’re using -le (less than or equal to) and this gives us the output:

Do While

$i = 6
    Start-Process notepad
while($i -le 5)

Do While loop is basically a normal While loop but with the difference that a Do While will always run its code block at least once, even if the While statement is false from the start like in the above example.

Bonus round – Do Until

$i = 1
    Start-Process notepad
until($i -eq 5)

Very similar to the While loop but instead of doing something WHILE the statement is true, Do Until does something UNTIL the statement is true.

General information about loops

First of, loops are great, please take the effort to learn how to use them. It can save so much time and make daunting tasks quick and easy.

You can break out of loops early if you want by using the command Break. Useful for stopping a loop if the goal is achieved earlier than expected or if you encounter an error.

It is also possible to skip ahead to the next cycle without executing all or parts of the current cycle by using the command Continue.

$num = 1..5

foreach($n in $num){
    "Start of loop $n :)"
    if($n -eq 3){
    elseif($n -eq 4){
        "Woops I stopped early :S"

    "End of loop $n :("

As mentioned in the last post about loops, you can manually break out of them by pressing CTRL + C.

If you are using Powershell 7 (not officially available in ISE), then you can use -Parallel on Foreach-Object to run the loop with several threads, allowing your loop to be even quicker!
If your stuck in ISE with PowerShell 5 you can still get multithreading in your loops but you have to do the work yourself, we might take a peak at it in a future post πŸ™‚

There is so much more that can be said, showed and explained about loops in Powershell but I try to make these posts, especially the beginner tutorials, short and interesting. It should be easy and fun learning Powershell. We can geek about the deep questions and problems when you get there πŸ˜‰

We’ll be seeing different loops, but mainly Foreach/Foreach-Object, in other posts since I use them a lot.

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

PowerShell – Stuck in the loop

Having to perform the same repetitive task over and over again is not fun and only dulls the brain. But when it has to be done, PowerShell doesn’t mind and is ready to help.

Like in many programming languages Powershell provides us with a few different loops.


Might be the most straight forward loop and one you’ll use often.
This loop is used in one liners and takes pipeline input.

ForEach-Object can be shortened down to ForEach or just simply a percent sign, %.


If you are following along, open at least one Notepad before proceeding so that you have something to collect. If you have a Notepad already opened with unsaved text in it, save it before trying these since we will be closing ALL Notepad processes.

# EXAMPLE ONE #################################################

# Foreach-Object

$notepads = Get-Process notepad
$notepads | ForEach-Object{ Stop-Process $_ }

# EXAMPLE TWO #################################################

# Foreach-Object - Multiple commands and source directly from a command

Get-Process notepad | ForEach-Object{ Write-Host "Stopping process $($ with process ID: $($_.Id)" ; Stop-Process $_ }

# EXAMPLE Three ###############################################
Get-Process notepad | % { Stop-Process $_ }

In the first example we load a variable with all Notepad processes.
Next we pipe that variable to ForEach-Object and within the script block (the curly brackets) is the code we want to run for each Notepad process.
In this case we are running Stop-Process.
$_ represents the current object in the pipeline and the current item (Notepad process) being looped.

In example two we skip the initial $notepads variable and instead directly pipe the input to ForEach-Object.
This time we’re going to run two commands for each Notepad process and we will do so by using the semicolon ( ; ).
This keeps it a one liner but still allows us to use several commands like if we had several lines.
Using Write-Host we output some information to console about the processes we are stopping.

$_ has several attributes with information we might be interested in, like Name and Id which we can access by typing $_. and the attribute name (Name/Id).
Since it is within a string the .Name or .Id would be considered text, so we use a dollar sign and two parentheses, $(), to make it a temporary variable.

The third example is just to showcase using the percent sign alias for ForEach-Object.


Sibling to ForEach-Object, ForEach is more used for scripts. Noticeable change is that ForEach does not use $_ but instead assigns a named variable.
This is my favorite loop.


# Simple Foreach loop #######################################

$notepads = Get-Process notepad

foreach($notepad in $notepads){
    Stop-Process $notepad

# More advanced Foreach loop ################################

$notepads = Get-Process notepad
$count = $notepads.count
$i = 1

foreach($notepad in $notepads){

    # These variables will be overwritten each loop
    $processID = $ 
    $name = $notepad.Name

    Write-Host "[$i/$count] Stopping process $name with process ID: $processID"

        # Using "-ErrorAction Stop" makes every error a terminating error which will trigger our try catch. 
        Stop-Process $notepad -ErrorAction Stop
        # Write a warning when we receive an error trying to stop the process. This will log some info we decide (name and pid) and then the error message returned by Powershell. 
        Write-Warning "Error when stopping process $name with process ID: $processID. Error message was: $($_.Exception.Message)"

    # Increase $i by one

Simple foreach loop starts with saving the Notepad processes to a variable, but this time we’re not using the pipe to pass the values to the loop.

So the code goes like “for each $notepad in $notepads”.
$notepads is our variable we created and added the process data into.
$notepad is a new variable that the foreach loop will assign a new value to each time it loops, similar to $_.
in” is just a keyword used here, gives a nice flow to it.
The $notepad variable doesn’t have to be named like that, you could name it $itSureIsNiceLearningPowerShell or whatever you like πŸ™‚

For this short example it doesn’t really make sense and you’d be better of using ForEach-Object, but lets move on the next example.

In the more advanced example we get a better taste of using the foreach loop but we start with some variables.
We get a variable containing the count of notepads, so we know how many Notepad processes we have caught.
Next up with create the $i variable and set it to 1, this will be used to tell us which Notepad process we are currently processing (like 2/7, 3/7, 4/7 and so on).

Inside the loop we create two more variables, these variables will be overwritten every time it loops.

The information we write to the console is the process name and Id, but also [$i/$count] this is useful when looping many items so that you know how far along the loop is.

The output will look like this if we had 3 Notepad processes:

We add some error handling to our loop with a Try Catch block.
The Stop-Process command has ErrorAction set to Stop which will make all errors “terminating errors” which will mean that Try Catch triggers on all errors.

If we encounter an error we write a warning with some useful information and add the Exception Message thrown by PowerShell, this is the red text information you get from an error.

Lastly we increase the $i variable by one.

Powershell has several more loops that we’ll discuss in the future.

And if youΒ΄re ever stuck in the loop, remember you only have to press CTRL+C πŸ˜‰

What have loops solved for you in Powershell?

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

Powershell – Variables not wearables

$introToTutorial = “Saves time, effort and decreases hair pulling – Get your variables now!”

Variables in Powershell allows you to save stuff for later and access it when you need it again.
We’ve used variables in previous tutorials but lets take a better look at them.

A variable in Powershell starts with a dollar sign ($) and then its name, just like $introToTutorial.
To assign a value to the variable you simply add a equal sign (=) and then the value, just like we did above with the intro.

Lets write some examples:

# Variable with a string as value
$myString = "Ohh so this is a string ey?"

# Variable with a int as value
$myInt = 50

# Variable containing all currently running processes on my local computer
$myProcesses = Get-Process

When we want to access the data saved in our variables we simply call their names:

We can also use it in a command like this:

$processName = "calculator"

Write-Host "Searching after process $processName..."

Get-Process -Name $processName
Output from running the above Powershell code

Now you might have noticed that I make certain letters of the variable names upper case, like in $myString.
I do this for the readability since the variable name often contains several words. There are many different standards of how to name and capitalize your variable names but the important thing is to chose one and stick to it.
Since Powershell is (for the most parts) case insensitive it doesn’t matter, if you name the variable $myString, you can still call it with $mystring or $MYSTRING or any combination of upper and lower case letters.

The naming of the variables can also differ between how you have been taught but I always try to name them somewhat descriptive.
$myString is fine for an example, but in something larger it just describes the type of object the variable holds.
A better example could be:

# Set the start date to yesterday
$startDate = (Get-Date).AddDays(-1)

# Set the end date to now
$endDate = Get-Date

# Location of the log files
$logFileLocation = "C:\Temp\Logs"

You can also save script blocks in variables as well as hash tables, lets look at how we set the variables and how to make use of them.

# Script block containing our custom code 
$scriptBlock = {
    $date = Get-Date -Format "yyyy-MM-dd HH:mm"
    Write-Host "[$date] Im in a script block, look at me now!" -ForegroundColor Yellow


Write-Host "Huh ok..."

& $scriptBlock

We create the script block variable by setting the value to a few lines of code, wrapped in squiggly brackets { }.
But when we call the variable by its name, like we’ve done before, it only outputs the code we want to run.
Now that can be useful if you wish to log the exact code you are about to run, but we want it to run!

That’s when Powershells call operator “&” steps in.
As you see in the above image, and when you try the code yourself, when we run “& $scriptblock” it executes the code and gives us the yellow Write-Host with the current date in the text.

We’ll be using the call operator loads of times in future tutorials but lets talk about it and it’s cousin the dot source operator so you get a grasp of them.

The call operator (&) allows you to execute a command, script or function. When you use the call operator, what ever you execute is done so in a new scope.
We have yet to talk about scopes, but Powershell scopes could be referred to as different dimensions, where variables aren’t shared.

This means that when we run “& $scriptblock” the $date variable is not available to us after, unless we have added a $date variable outside of the script block.

The reason why we see the command we just ran is because I have not saved this as a file, if we save and run it, it looks better in the console window of the ISE

Now not sharing the variables can sometimes be exactly what we need, it can allow us to run scripts and functions without the risk of their variable names colliding with ours.

But what if we do want the variables to carry over to our script, accessible in our scope?

That is when the dot source operator (.) steps in.
Lets call our script block variable with the dot source operator instead and see if that makes a difference.

Alright, that’s awesome, but lets move on!

Hash tables and something called splatting, not as weird as it sounds.

# Hash table with colors for Write-Host
$hashTable = @{
    ForeGroundColor = "Yellow"
    BackGroundColor = "Red"

Write-Host -Object "Wow look at this" @hashTable

The hash table is constructed almost the same way as the script block, but with Powershell’s splat operator, the “@” sign, before the squiggly brackets.
And this time we’re not adding Powershell commands to it but rather property names and their values.

Now look closely at the Write-Host line.

Write-Host -Object "Wow look at this" @hashTable

We use both the -Object property to add the text we want to output but we also add our hash table variable, although in a different way, with @variableName instead of $variableName.

You can have all the properties in the hash table or just some and then fill in the rest when typing the command, just like we did above with Write-Host.
The use case for this is for example when you have a really long command with loads of properties or perhaps long values, or when you want to change the properties or values that should be used before executing the command, useful in more advanced scripts.

We’ll certainly use all of this again in future projects and tutorials so don’t get stressed if you don’t fully understand it yet.
The best way of learning this is by doing so try and also practice these examples and examples of your own to really get a hang of it.

This was a longer post but I have also not posted in quite a while so felt like we needed this!
Trying to keep these posts from diving too deep so they are easier to consume for someone that is new to Powershell and scripting.

If something needs to be explained better or if it’s too easy, please comment and let me know.
I am planning some more advanced posts but have tried to focus on the basics.

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

Powershell – Try to Catch me

In times like these when the real world is a bit crazy, it can be good to dive into something else and let the mind concentrate on learning a new skill.

So lets wash our hands and jump into a Powershell tutorial!
This time we’ll be talking about how we can easily handle errors that might occur in our scripts.
As always with Powershell, there are multitudes of different ways to do this but we’ll talk about the one I prefer, Try Catch.

    Get-Process "Wrong name of process" -ErrorAction Stop
    Write-host "Oh oh error when getting process information!" -ForegroundColor Red

The above code is very bare bones what is needed but doesn’t really add much value.

Before we improve the example, lets talk about each block and also mention a third block that we are not using, called Finally.

The Try block comes first and within its script block (The wiggly brackets { } ) is the code that we want to catch errors from.

You’ll notice that we have added the parameter ErrorAction with value Stop to the Get-Process command.
This is because not all errors in Powershell is considered to be terminating errors, and only those kind of critical errors are caught by the Try Catch statement.
But we want all errors for Get-Process to be handled as terminating errors so we can apply our own logic and handling to them.

Script blocks will be something that you’ll come across a lot in Powershell, both when building scripts but also in one-liners.
They allow multiple lines (in a one-liner you’d separate the commands using semicolons ; ).

The Catch block is the second part of this statement and contains all the code that will be run once an error from the Try block occurs.

In the example above we only write to the console using Write-Host saying that we’ve found an error, not very useful at all!
Using Try Catch suppresses Powershell’s normal output to the console so based on our example, we wont know what error occurred since the only information we now receive is “found an error”.

We’ll add some more useful things to the Catch block later!

Try and Catch are both mandatory but there is a third part that is optional called Finally.

    Get-Process "Wrong name of process" -ErrorAction Stop
    Write-host "Oh oh error when getting process information!" -ForegroundColor Red
    Write-Host "Phew finally done!" -ForegroundColor Green

The code in the Finally block will always be run, even if the error stops the script from continuing or if you yourself have added a exit or return command to the Catch script block.

Personally I don’t use Finally that much, very rarely actually, but it can be useful if you have code that you need to run regardless of the success of the code in the Try block.

Lets improve!

# Name of the process we want to gather information about using Get-Process. Seems to be misspelled hmm..? 
$processName = "Shellpower"

# Get information about process
    $process = Get-Process $processName -ErrorAction Stop
# Only comments are allowed to be between the Try block and the Catch block
    # Exception message, the actual error reported by Powershell
    $exception = $_.Exception.Message

    # Output a warning to the console about the error
    Write-Warning "Error when trying to get information about the process $processName. Error message was: $exception"    

So we’ve obviously added a bunch of comments and changed the process name to use a variable with the value “Shellpower” which is a name we wont be finding among our processes.

Those things aside, we now have a variable called $exception.
This variable will pull the current exception message, saved in the variable we can use it to output or save the information easily.

If we didn’t use the Try Catch block we’d receive something like this:

With our example, we instead receive this:

WARNING: Error when trying to get information about the process Shellpower. Error message was: Cannot find a process with the name “Shellpower”. Verify the process name and call the cmdlet again.

With this method you can add a more customized error message while still retaining the original error message.

You can add several commands to the Try block which can be enough if all you want to do is catch and report/log the errors.
I personally try to keep them to one command each and then add a customized error text which gives more information, since the exception messages can be a bit lacking.

Another option could be to store the information in a log file, write it to a SQL database or maybe even have the script do something when it encounters specific errors.

There are loads of possibilities with this but for the sake of keeping this bite sized we’ll stop here.

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

Powershell – From deeply flawed to very powerful

“Powershell is such a great product because I’m a deeplyflawed human being.” – Jeffrey Snover, the creator of Powershell

Powershell is that friend that you can always rely on. When your memory fails you, Powershell is there to help!

In this post we’ll be talking about some of the features in Powershell that can assist you on your journey.
Lets begin with the Get-Help cmdlet.

Notice that I did not type -Name. That is because the Name parameter has a positional value of 0, which means that the first entered value will be inputted as Name.
More about this in a later post.

Type the cmdlet you want help with after Get-Help and you’ll see the above information.
At the bottom of the image you can see I’ve added -Detailed, and just like it sounds this gives more detailed information about the cmdlet.

The information is also available online, just search after the cmdlet name or what you want to do and you’ll find the Microsoft article.
For example here is the Get-Process article.

The syntax is explained here, I’ll paste the main part below:

<command-name> -<Required Parameter Name> <Required Parameter Value>
[-<Optional Parameter Name> <Optional Parameter Value>]
[-<Optional Switch Parameters>]
[-<Optional Parameter Name>] <Required Parameter Value>

Tab auto completion
Now this is a feature that you’ll be using all the time!
Start to write something, can be cmdlet names, parameters, variable names etc., and then hit tab and Powershell will try to guess what you wanted to type.
For example typing ‘get-pro’ and then hitting the ‘Tab key’ will give you ‘Get-Process’.
You can press tab several times, if what you typed could be resolved to several names than you’ll go through the list.
Pressing ‘Shift + Tab’ will go backwards in the list.

If a cmdlet can’t be auto completed, then either you’ve typed it incorrectly or the cmdlet isn’t loaded.
Now we haven’t started talking about modules and functions yet, but Powershell comes with some cmdlets builtin and then you can add more on top of those. We’ll look at that in a future post.

This is Microsoft’s context-aware code completion feature and it is very useful.
In Powershell ISE you have access to it automatically but if it doesn’t show up, which sometimes happens, you can get it to show by pressing ‘CTRL + Space’.
In the version of Powershell I’m running, Intellisense is also available in the shell (5.1.15063.1805), also by pressing ‘CTRL + Space’.

Intellisense in ISE with cmdlet names.
Intellisense in the shell for parameters.

Play around with these features and get comfortable with them and it will help you going forward!

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

Powershell – But I only want to see this

In this post we will continue to discover basic functionality of Powershell by looking at how we can select what information we wish to display when running a Get-* cmdlet.
We will also touch on how to check what version of Powershell we are running.

Last post I talked a bit about different Powershell versions and you might wonder how you can tell what version of Powershell is running on your machine.
The answer can easily be found in a special Powershell variable called $PSVersionTable.

Open up Powershell (both the shell or ISE is fine) and type in the variable name and hit enter.

PSVersion is the one we are interested in.

Check this link for information on installing different versions of Powershell.

Now, if we instead move on to the main part of this post and to what we actually want to see.

When we used Get-Process to get all processes named ‘calculator’, we were presented with a couple of attributes.

This is fine but you might feel that some of it is a bit abundant.
Again, we have a couple of different ways we can chose what to display and we’ll look at a few of them below.

Alias = Alternative name for a Cmdlet, function or parameter. Often used to shorten how much you need to type.

This cmdlet formats the output in a table structure and displays only the attributes you choose.
However if you do not enter anything after Format-Table it will display all attributes available. In some cases you’ll need to enter the wildcard character * for all attributes to display (depends on the cmdlet).

This cmdlet is used a lot when you want to output a few attributes on the screen.
A good example for when Format-Table is perfect to use would be when you want to check all your Chrome processes and their load on CPU.

Format-Table has a very handy parameter which is called -AutoSize that auto sizes the column width.

Alias: FT (Not case sensitive)

Works like Format-Table but displays the output in a list.
Does not have the -AutoSize parameter.

Format-List is also used a lot and comes in handy when you want to display a lot of attributes for one process.

Alias: FL (Not case sensitive)

Now this one is a bit different from the other two and is used more for scripting, but still useful if all you want is to display some information on your screen.

Select-Object will output in either list or table format, based on how many attributes are present.

This cmdlet will be shown many times on this blog and is also easy to play with so try to explore it on your own too!

Some common parameters and their usage:
-First 1
Displays the first object in the list, you can enter any number to display more or less.

-Last 1
Works just like -First but instead displays the last object/objects.

-ExpandProperty Name
Only accepts one property but expands it. We’ll go into more details about this feature further down the line but it basicallys opens up the property you selects. Some properties might include several values so then you’ll see it’s sub properties.
If we take the Name property as an example, when using ‘-ExpandProperty name’ it will display the name only and not the ‘header/title’ above it.

Displays only unique values.

Alias: Select

There is more to say about all of these cmdlets and sometimes we only touch lightly on a subject, but don’t worry, we’ll be seing a lot of these in the future!

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next

Development Powershell Tutorials

Powershell – Introduction

Powershell logo

“One tool to rule them all”
“Those who don’t automate are doomed to repeat themselves”

Powershell, the command line framework and scripting language from Microsoft.
In the beginning this was a Windows only feature (Windows Powershell) but has since Powershell Core and
Powershell 7 gone to open-source and is available on other platforms.
Since I am a Windows guy we’ll be focusing on Powershell from a Windows perspective.

Windows 10 comes with Windows Powershell 5 preinstalled.
Simply type Powershell into your start menu’s search bar and you’ll see two applications:
Powershell and Powershell ISE (x86 and x64)

Powershell or Powershell.exe is where you write Powershell one line at a time, much like the
Command prompt (CMD) that many has seen before.
The commands used in Powershell is called ‘cmdlets’ and are named like Verb-Noun.

Powershell ISE is the other application which ships with Windows and it has been the primary editor for Powershell scripts.
Microsoft has now stopped developing the ISE and is instead promoting the use of Visual Studio Code (VSC) with a Powershell plugin.
Visual Studio Code is free to download and use.
ISE is still very much usable but VSC is the future and if you do come from a programming background then VSC will most likely be preferable.

So what can we do with Powershell? Well everything basically!

But a good place to start is with the cmdlet Get-Process.
This will show the processes running on your computer.
See detailed information here:

Powershell is case insensitive, get-process/Get-Process/GET-PROCESS etc. all work the same.

Lets add a parameter, -Name and then lets grab all processes named Chrome:

Get-Process -Name Chrome
Using Get-* cmdlets is risk free since you only get information.

Consider this scenario: You’ve been using an application, in our case the built in calculator, and the program has stopped responding and you are now unable to close it.
You open up Powershell. You know about the Get-Process cmdlet and that you can use the Parameter -Name to only get processes named ‘Calculator’.
But now what?
Along comes the mighty Stop-Process !

This cmdlet, much like its more harmless sibling, also features the parameter -Name.
But there are two ways of doing this:

Stop-Process -Name Calculator
Get-Process -Name Calculator | Stop-Process

Both will have the same outcome, the process Calculator will close.
The second alternative uses the character | called ‘pipe’ to, you guessed it, pipe the information from Get-Process to Stop-Process.
This is something that is used in Powershell all the time, expecially outside of ISE where you only work one line at a time.

When you run the Get-Process cmdlet you are returned an object, this object holds information like ProcessName or ID of the process and much more.
When you pipe the Get- cmdlet to the Stop- cmdlet, your are then redirecting that object from being displayed on your screen to being used to fill in the parameters of the Stop- cmdlet.
This means that you can’t pipe whatever you want to everything but these two are in the same ‘family’ and have been built to work togheter.

The object being pushed through the pipeline is saved in the temporary variable called ‘$_’.
We will talk more about variables in other posts but think of variables like a tool chest with labeled drawers.

That’s it for this introduction to Powershell as I’d like to keep these bite sized for beginners.
A big part of learning powershell is to just test it yourself and exploring what happens (just be a bit careful with the Stop-Process or you might have to restart the ol’ computer πŸ˜‰ ).

As always, continue to learn and evolve your skills, see you in the next one!

Do you want to know more? Here is a list of tutorials to check next