Tag Archives: PSMonday

PSMonday #38: January 16, 2017

Topic: Foreach-Object II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

We’re back today to wrap up the ForEach-Object cmdlet, with a few additional examples.

The Get-PSDrive cmdlet’s purpose is to return the logical drives on the computer, to include mapped drives, as well as drives exposed by various PowerShell providers. These include the alias drive — where the aliases are stored — the function drive — where functions in the current session are stored, and current user and local machine hives in the registry, as HKCU and HKLM, respectively.

Therefore, if you didn’t already know, you can search the registry from inside PowerShell, just as if it were a drive on the computer. That’s the purpose of a PSProvider. It can present various data stores, as though they were drives on the computer.

Here’s a filtered Get-PSDrive command, and the results it produces.

Get-PSDrive | Select-Object -Property Name,Root

Name     Root
----     ----
Alias
C        C:\
Cert     \
D        D:\
Env
Function
HKCU     HKEY_CURRENT_USER
HKLM     HKEY_LOCAL_MACHINE
S        S:\
Variable
WSMan

We did something like the upcoming example when we learned about the foreach language construct. In this example, we’ll deconstruct the objects produced by Get-PSDrive, in order to write out strings based on two properties of the objects — Name and Root. You probably wouldn’t want to do this, but nonetheless this example offers us a collection to loop through with the ForEach-Object cmdlet.

Get-PSDrive | ForEach-Object {
    "PSDrive Name : $($_.Name) || Root: $($_.Root)"
}

PSDrive Name : Alias || Root:
PSDrive Name : C || Root: C:\
PSDrive Name : Cert || Root: \
PSDrive Name : D || Root: D:\
PSDrive Name : Env || Root:
PSDrive Name : Function || Root:
PSDrive Name : HKCU || Root: HKEY_CURRENT_USER
PSDrive Name : HKLM || Root: HKEY_LOCAL_MACHINE
PSDrive Name : S || Root: S:\
PSDrive Name : Variable || Root:
PSDrive Name : WSMan || Root:

The next example begins by assigning the $Numbers variable a range of values from 1 to 10, thus making this variable an array.

$Numbers = 1..10
$Numbers

1
2
3
4
5
6
7
8
9
10

In each of the next two examples, we’ll make use of our numbers variable. This first example will use the foreach language construct that we covered prior to the ForEach-Object cmdlet. We set up the foreach using the foreach keyword and use $Number (singular), to use as the current value in the array.

Foreach ($Number in $Numbers) {

    Write-Output -InputObject "The current number is $Number."
}

The current number is 1.
The current number is 2.
The current number is 3.
The current number is 4.
The current number is 5.
The current number is 6.
The current number is 7.
The current number is 8.
The current number is 9.
The current number is 10.

In the below example, we’ll do the exact same thing as we did above, and iterate though each member in an array. The ForEach-Object cmdlet can do the same thing as the foreach language construct, it just does it a little differently. Instead of a variable you choose, we use $_, or $PSItem. Instead of foreach being the first word in the command, we pipe to the ForEach-Object cmdlet.

$Numbers | ForEach-Object {

    Write-Output -InputObject "The current number is $_."
}

The current number is 1.
The current number is 2.
The current number is 3.
The current number is 4.
The current number is 5.
The current number is 6.
The current number is 7.
The current number is 8.
The current number is 9.
The current number is 10.

In closing out ForEach-Object, let’s discuss some final differences with it, and the foreach language construct.

The foreach language construct is faster than the ForEach-Object cmdlet. This is because foreach puts the entire collection into memory before it begins to iterate over each item in the collection. This could be a problem, however, if there’s a chance you’ll run out of memory before you’re done processing the entire collection. While the ForEach-Object cmdlet may be slower, it’ll consume less memory.

We’ll continue with the For loop, next Monday.

PSMonday #37: January 9, 2017

Topic: Foreach-Object

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Now that we have a basic understanding of the foreach language construct, we can move on to the ForEach-Object cmdlet. First, let’s consider the name of the cmdlet, as there are some similarities with some others. The noun — remember the verb-noun naming convention — is object. Let’s find all the commands with that same noun.

Get-Command -Noun Object | Select-Object CommandType,Name

CommandType Name
----------- ----
   Function Show-Object
     Cmdlet Compare-Object
     Cmdlet ForEach-Object
     Cmdlet Group-Object
     Cmdlet Measure-Object
     Cmdlet New-Object
     Cmdlet Select-Object
     Cmdlet Skip-Object
     Cmdlet Sort-Object
     Cmdlet Tee-Object
     Cmdlet Where-Object

If you’ve used some of the above commands, then you may recognize that many of these commands are used with the pipeline. This is to say, that we often send a command’s resulting objects to one of these commands.

In fact, take a look at the Get-Command, command we ran: We piped the objects created by Get-Command to the Select-Object cmdlet for further processing and filtering. That’s how we’ll use ForEach-Object, too; we’re always going to pipe to it.

Let’s begin with some conceptual examples of the ForEach-Object cmdlet. As we saw in a previous PSMonday, the first part of this example is the Microsoft help’s suggestion, and the second part of this example is how you’ll see me use the cmdlet.

<command> | ForEach-Object {<command_block>}

<command> | ForEach-Object {
    <command_block>
}

As we’ve stated before, always use full cmdlet names unless you’re using the command in a onetime use scenario. If you’re pounding out PowerShell commands with no intention of keeping them, then you can use either of the ForEach-Object aliases, as demonstrated below. This is important: foreach is an alias for the ForEach-Object cmdlet when it is used in a pipeline. When it’s not used in a pipeline, such as we saw in the last two weeks, it’s treated as the foreach language construct, and not as an alias for ForEach-Object. This can cause some confusion, and so it’s important to understand this distinction.

<command> | foreach {
    <command_block>
}

<command> | % {
    <command_block>
}

Before we put things back on hold until next Monday, let’s take a look at a real-world example. Both of the following parts of this example do nearly the same thing. The difference is that one, the second half includes the string “Item: ,” and two, it uses the $PSItem automatic variable, instead of $_. This variable — regardless of which you use — represents the current object in the pipeline. $PSItem was introduced in PowerShell 3.0.

1,'string1',2,'string2' | ForEach-Object {
    Write-Output -InputObject $_
}

Write-Output -InputObject '------'

3,'string3',4,'string4' | ForEach-Object {
    Write-Output -InputObject "Item: $PSItem"
}

1
string1
2
string2
------
Item: 3
Item: string3
Item: 4
Item: string4

In the above example, we sent four objects — two integers and two strings — down the pipeline to each of the ForEach-Object cmdlet examples. In looking at the first part of the example, $_ was 1 the first time the ForEach-Object cmdlet ran, it was ‘string1’, the second time the ForEach-Object cmdlet ran, 2 the third time, and ‘string2’ the final time the loop executed.

We’ll be back next week to help solidify how we use the ForEach-Object cmdlet.

PSMonday #36: January 2, 2017

Topic: Foreach II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Back again to discuss, and close out, the foreach language construct. This is the first looping construct we’ve seen so far.

Today, one of the things we’ll do, is nest a foreach inside of a foreach. In case it hasn’t been mentioned yet, all of these language constructs can be nested inside of each other. In fact, this is often a requirement. It all depends on the problem, or problems, that you need to solve. This is a great reason to ensure you understand all of the conditional constructs.

We’ll start today’s PSMonday by creating two variables. One, the Colors variables will hold the same four colors from last week. The second variable, the Animals variable, will also hold four values: dog, cat, bird, and frog. Take a look at the below example, and the explanation further below.

$Colors = 'red','blue','green','gray'
$Animals = 'dog','cat','bird','frog'

Foreach ($Color in $Colors) {
    Write-Output -InputObject $Color

    Foreach ($Animal in $Animals) {
        Write-Output -InputObject $Animal
    }
}

red
dog
cat
bird
frog
blue
dog
cat
bird
frog
green
dog
cat
bird
frog
gray
dog
cat
bird
frog

Admittedly, this is a little difficult to follow. Before we walkthrough what’s happening here, let’s modify how we display the values in the Color variable. Additionally, we’ll modify how we display the values in the Animal variable, as well. This will help us better follow these nested foreach loops. Colors will have two dashes on both sides, and animals will have a right, angle bracket before the animal name.

Foreach ($Color in $Colors) {
    Write-Output -InputObject "--$Color--"

    Foreach ($Animal in $Animals) {
        Write-Output -InputObject "> $Animal"
    }
}

--red--
> dog
> cat
> bird
> frog
--blue--
> dog
> cat
> bird
> frog
--green--
> dog
> cat
> bird
> frog
--gray--
> dog
> cat
> bird
> frog

From the previous examples, you may already be able to determine exactly what’s happening. In case you don’t, let’s walk through the looping that is taking place.

After we set the two variables, Colors and Animals, we enter the first foreach. In here, we echo the first color. Then we enter the nested, or the second foreach loop, and loop through all four animals. We then return to the outermost foreach, and echo the second color. Again, we loop through all the animals. We continue this until we’re all out of the colors in the Color variable, and we do a final loop through the animals.

Here’s the last example. Although we won’t be working with nested foreach loops, I think it’s important to see a potential, real-world example. With Get-Service, and most other properly written cmdlets and functions, we can pipe to the Select-Object cmdlet, and return just the properties in which we’re interested.

Get-Service | Select-Object -Property Name,Status -First 3

Name                       Status
----                       ------
AdobeARMservice           Running
AdobeFlashPlayerUpdateSvc Stopped
AeLookupSvc               Stopped

Let’s assume we don’t want to return objects — for some reason — and instead just want to return strings made up of the two above properties, separated by a colon. It’s not really practical, but it will provide a bit more of a real-world foreach example. To accomplish this, we’d need to loop though the results of Get-Service.

Foreach ($Service in Get-Service | Select-Object -First 3) {
    "$($Service.Name) : $($Service.Status)"
}

AdobeARMservice : Running
AdobeFlashPlayerUpdateSvc : Stopped
AeLookupSvc : Stopped

As we can see, the items in our collection (the $Service in Get-Service), can be taken directly from the results of a command, without the need to assign everything to a variable first. While this made not always be the best idea for the sake of readability, it’s something you may see one day.

Up next week, is the ForEach-Object cmdlet.

PSMonday #35: December 26, 2016

Topic: Foreach

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

A day late, but here we go.

Like the If statement, the foreach statement is an often used language construct. In fact, I wouldn’t be surprised to find out that it was the second most used, right after the If statement. The foreach differs, however, in that it is a looping construct. This is to say that we use it to loop through a collection, or a group, of items.

As we’ve done in the past, let’s start with the conceptual format of the foreach construct. There’s always a few ways to write the same thing. The first part of this example, shows how it’s displayed in the PowerShell help, and the second part, is how I write, my foreach statements.

foreach ($<item> in $<collection>){<statement list>}

Foreach ($<item> in $<collection>) {
    <statement list>
}

The most common collection we’ll loop through using a foreach is an array. An array is a data structure, designed to store a collection of items. Before we get there, consider that many variables are only ever assigned a single value, such as in the below example.

$Computer = 'Server01'
$Computer

Server01

In the previous example, the Computer variable only held a single, string value of “Server01.”

An array lets us get away with a single variable holding multiple values. Let’s start with the multiple values of ‘red’, ‘blue’, ‘green’, and ‘gray’. Each of these is an item, but together, they are a collection; they’re an array. Before we actually work with this array, we’ll assign it to the Colors variable. The decision to use a plural variable, is intentional.

$Colors = 'red','blue','green','gray'
$Colors

red
blue
green
gray

With this variable set, we can loop through each item in the collection — each value in the variable — using foreach. The first time we enter the foreach, the Color variable (singular), will be ‘red.’ The second time we loop through, the Color variable is ‘blue.’ The third iteration into the foreach, it’s ‘green,’ and on the final pass, the Color variable is ‘gray.’

Foreach ($Color in $Colors) {
    Write-Output -InputObject "The `$Color variable is: $Color"
}

The $Color variable is: red
The $Color variable is: blue
The $Color variable is: green
The $Color variable is: gray

This item variable, could’ve been any word; however, we chose to use Color, because it made the most sense. The decision to use a single variable was intentional, too. Here’s the same example as above, however, we’ve changed Color to Hamburger. It makes no sense, but it still works.

Foreach ($Hamburger in $Colors) {
    Write-Output -InputObject "The `$Hamburger variable is: $Hamburger"
}

The $Hamburger variable is: red
The $Hamburger variable is: blue
The $Hamburger variable is: green
The $Hamburger variable is: gray

We’ll likely wrap up the foreach language construct next week, just in time to work with the ForEach-Object cmdlet. They’re different.

PSMonday #34: December 19, 2016

Topic: Switch Statement IV

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Here we are again. It’s Monday morning and we’re discussing the Switch language construct; we’re wrapping it up, in fact. Last week we determined that Switch included a Wildcard parameter. Today we’ll discuss the Regex parameter, and a bit more.

The below example does a few things. To make this as easiest as possible to follow, I’ve numbered both the list, and the matching code:

  1. Write a string to the host (the screen), to help indicate what the user should do.
  2. Create a prompt to accept the user’s input, and assign that user’s input, to the LastName variable.
  3. Help the user determine their Human Resource representative using a Switch construct and the Regex parameter.
# 1
Write-Output -InputObject 'Enter your last name to determine your Human Resources representative.'

# 2
$LastName = Read-Host -Prompt 'Enter your last name'

# 3
Switch -Regex ($LastName.ToLower()) {
    '^[a-g]' {"Please see Barbara in Room 202."}
    '^[h-m]' {"Please see Mark in Room 203."}
    '^[n-z]' {"Please see Allison in Room 204."}
    default {"$LastName did not work, please try again."}
}

In #3, we’ve set up the Switch statement the same as the other examples; however, we’ve included the Regex parameter. Additionally, the test-value uses the ToLower method, against the value stored in the LastName variable. This ensures our value is in lowercase before we start checking the conditions inside the Switch.

What these conditions do is check the first letter of the last name. Depending on the letter, it’ll report the proper HR representative to visit. One of the things that this example also includes is a default condition. While I could’ve mentioned this week’s ago, I’ve saved it. This is the action to take if there’s no conditional match. Think of this as the Else in an If-Else statement. This could’ve have been included in any of the previous Switch statements we’ve seen in the last three weeks.

Now for the last two examples before we close out the Switch. The $_ variable is something we usually only see when we use ForEach-Object — an upcoming language construct. Even so, it has a purpose in the Switch construct, too. In the below example, it’s acting as the current element in the array. It’s ‘one,’ the first time we enter the Switch, it’s ‘two,’ the second time, etc. Take a look at the example and make sure you can determine why the results were returned the way they were. $PSItem was introduced in PowerShell 3.0, and it does the exact same thing as $_.

$Array = 'one','two','three','four','five'

Switch ($Array) {
    {$_ -eq 'one'} {'One found.'}
    {$PSItem  -eq 'three'} {'Three found.'}
    {$_ -eq 'six'} {'Six found.'}
}

One found.
Three found.

This final example is here to help indicate that we can use the $_, or $PSItem, in both the condition, as we saw above, and in the action, as we’ll see below.

$Servers = 'DC01','DC02','DC03','WEB01'

Switch ($Servers) {
    'DC01'{"Run command against server $_."}
    'DC02' {"Run command against server $_."}
    'WEB01' {"Run command against server $_."}
    {$_} {"Add computer to log file ($_)."}
}

Run command against server DC01.
Add computer to log file (DC01).
Run command against server DC02.
Add computer to log file (DC02).
Add computer to log file (DC03).
Run command against server WEB01.
Add computer to log file (WEB01).

In closing, I should remind everyone that I can’t cover everything about a topic, and so it’s important to finalize your learning, or reviewing, by reading the full about file. You can read about the Switch statement here: Get-Help -Name about_Switch -ShowWindow. Most of it will be a review.

PSMonday #33: December 12, 2016

Topic: Switch Statement III

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

In case you haven’t noticed, I really like the Switch statement. Let’s start today’s PSMonday with this first example. It’s dead simple, and really only here for two reasons. One, it indicates we can use the semi-colon between sets of conditions and actions, and two, because I want to indicate the importance of the break statement. After the Switch finds its match in the third condition, it’s going to continue to check the other 23 conditions.

Switch ('c') {
    'a' {'A'}; 'b' {'B'}; 'c' {'C'}; 'd' {'D'}; 'e' {'E'}
    'f' {'F'}; 'g' {'G'}; 'h' {'H'}; 'i' {'I'}; 'j' {'J'}
    'k' {'K'}; 'l' {'L'}; 'm' {'M'}; 'n' {'N'}; 'o' {'O'}
    'p' {'P'}; 'q' {'Q'}; 'r' {'R'}; 's' {'S'}; 't' {'T'}
    'u' {'U'}; 'v' {'V'}; 'w' {'W'}; 'x' {'X'}; 'y' {'Y'}
    'z' {'Z'}
}

C

Let’s avoid that unnecessary work. In this example, after it hits the correct condition, it’ll leave the Switch statement. While there’s not much time savings in this example, there could be, if the Switch was doing more actions than simply echoing a letter to the screen. That’s something to keep in mind as you’re putting these together and considering the completion time of your code.

Switch ('c') {
    'a' {'A'; break}; 'b' {'B'; break}; 'c' {'C'; break}
    'd' {'D'; break}; 'e' {'E'; break}; 'f' {'F'; break}
    'g' {'G'; break}; 'h' {'H'; break}; 'i' {'I'; break}
    'j' {'J'; break}; 'k' {'K'; break}; 'l' {'L'; break}
    'm' {'M'; break}; 'n' {'N'; break}; 'o' {'O'; break}
    'p' {'P'; break}; 'q' {'Q'; break}; 'r' {'R'; break}
    's' {'S'; break}; 't' {'T'; break}; 'u' {'U'; break}
    'v' {'V'; break}; 'w' {'W'; break}; 'x' {'X'; break}
    'y' {'Y'; break}; 'z' {'Z'}
}

C

Instead of putting the true test-value in the parenthesis, we’ll use a variable in the next example. Additionally, we’ll take a look at the Switch’s wildcard parameter. In this example, we’re looking to match multiple conditions. Read it over, and we’ll run through the logic just below the example.

$Building = 'A-Center'

Switch -Wildcard ($Building) {
    'A*' {'Building: A'}
    'B*' {'Building: B'}
    'C*' {'Building: C'}
    'D*' {'Building: D'}
    '*North' {'Location: North'}
    '*South' {'Location: South'}
    '*Center' {'Location: Center'}
    '*East' {'Location: East'}
}

Building: A
Location: Center

The first four conditions, A*, B*, C*, and D*, are in place to match the beginning of the string that was assigned to the Building variable. The first condition, A*, is a match. The last four conditions in the Switch are in place to match the end of the string. Of those, the ‘*Center’ condition is a match. Like it does in other places, the asterisk is a wildcard character; it stands in, for one or more characters.

Here’s the same example, except that we’re outputting the appropriate actions to a variable, instead of writing them to the host. See if you can follow it. Notice that += assignment operators used in the last four conditions. This appends the value to the already existing value assigned to the Location variable.

$Building = 'A-Center'

Switch -Wildcard ($Building) {
    'A*' {$Location = 'Building: A'}
    'B*' {$Location = 'Building: B'}
    'C*' {$Location = 'Building: C'}
    'D*' {$Location = 'Building: D'}
    '*North' {$Location += ', Location: North'}
    '*South' {$Location += ', Location: South'}
    '*Center' {$Location += ', Location: Center'}
    '*East' {$Location += ', Location: East'}
}

$Location

Building: A, Location: Center

There’s still more to cover. We’ll be back with a fourth installment of the Switch language construct next week.

PSMonday #32: December 5, 2016

Topic: Switch Statement II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Okay, we’re back with more information on the Switch language construct. We’ll start where we left off: getting the Switch to act more like the If statement. In our first example we’ll do just that, and we do it with the break statement.

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'; break}
    4 {'Four'}
    3 {'Three (again)'}
}

Three

With the inclusion of the break statement, we exit the Switch construct the moment our condition is matched and action is completed.

Typically, I’ll include several break statements in my Switch statements. This is because once my condition is matched and the action completed, I’m typically ready to move past my Switch. In the below example, we’ll exit the Switch the moment a match is made and the action complete.

Switch (3) {
    1 {'One'; break}
    2 {'Two'; break}
    3 {'Three'; break}
    4 {'Four'}
}

Notice that I didn’t use a break statement on the last condition. It doesn’t make sense to include it. If we make it down to the last possible condition, I can be certain it’s not going to check anymore conditions, as there aren’t any more to check.

The switch statement can check collections, too. In this example, we evaluate the test-value of 4, and then the test-value of 2.

Switch (4,2) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'}
    4 {'Four'}
    5 {'Five'}
}

Four
Two

It’s probably a good time to indicate that the break statement can break things, as well. It’s not always a good idea that it’s used. In this next example, 2 is never evaluated because we exit the Switch the moment the action for 4 is complete.

Switch (4,2) {
    1 {'One'; break}
    2 {'Two'; break}
    3 {'Three'; break}
    4 {'Four'; break}
    5 {'Five'}
}

Four

That’s it for today. We have at least one more PSMonday dedicated to the Switch. Maybe two. Okay, probably two.

PSMonday #31: November 28, 2016

Topic: Switch Statement

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

The Switch language construct, also called the case statement in other languages, is a close relative to the If statement and its variations. As you work with If, be sure to consider Switch, as it can assist in a cleaner layout, and therefore, more easily read code. As mentioned previously, if your If statements are going past three levels, consider the Switch.

To start, here’s the basic, conceptual format. We consider a test-value in the parenthesis, determine the matching condition on the left, and then execute its corresponding action on the right.

Switch (<test-value>) {
    <condition> {<action>}
    <condition> {<action>}
    <condition> {<action>}
}

To begin, here’s a very basic example. We evaluate the test-value — it’s just a numeric 3 — and then find the matching condition. Once found (the 3 in our list of conditions), we’ll take the corresponding action, and write the word “Three” to the screen. Simple.

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'}
    4 {'Four'}
}

Three

Our test-value can also be an equation: 2 + 2 (= 4) and then down through the possible conditions, and take the appropriate action.

Switch (2 + 2) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'}
    4 {'Four'}
}

Four

There’s something we need to understand about the Switch construct, and that is that it is designed to look at all the conditions, no matter if it’s found one already, or not. Take a look at this example for clarification.

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'}
    4 {'Four'}
    3 {'Three (again).'}
    5 {'Five'}
}

Three
Three (again).

In the above example, we can easily see that although it found 3 in the list of conditions, it continued looking through the additional conditions, only to find another one that matched. What we should have done, is just included multiple commands inside the action, like the following two examples. Notice that in the first example, we use the semi-colon as a command separator, and in the second example, we use the line break (Enter).

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'; 'Three (again, but not really).'}
    4 {'Four'}
}

Three
Three (again, but not really).

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'
       'Three (again, but not really).'
    }
    4 {'Four'}
}

Three
Three (again, but not really).

Make sure you fully understand these examples before next week. We’ll start that PSMonday in an effort to show how to get our Switch statements to act a bit more like the If statement, to exit when our condition is matched, and action taken.

PSMonday #30: November 21, 2016

Topic: If, If-Else, If-ElseIf III

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

I failed to mention something last week. While I wouldn’t recommend you do it, you can rewrite this:

If (-Not(<condition>)) {
    <action>
}

to be this:

If (!(<condition>)) {
    <action>
}

I’m not mentioning this because you should use ! over -Not (ever, honestly), but just in case you see it being used. As I believed we’ve mentioned before, we only use aliases in onetime use scenarios, such as when you’re entering commands in your ConsoleHost or the ISE and have no intention of saving what you’ve entered. The ! is not a true alias, but it’s close enough to consider it one. This is a PowerShell community best practice, and one I’ll continue to pound in, at every opportunity I have.

Okay, on with this week’s If wrap-up.

Let’s get away from these conceptual examples. In this first example, we’ll assign values to two variables: $y will hold the numeric value of 5, and $z will hold the numeric value of 3. When we enter the If statement, we check both values. If both — and that’s key — of their values match, we’ll echo the word “If.”

$y = 5; $z = 3

If ($y -eq 5 -and $z -eq 3) {
    Write-Output -InputObject 'If'
}

If

Had we used the -or comparison operator, it would’ve echoed “If,” as well. Or, means that only one of the conditions would have to result In True.

If ($y -eq 5 -or $z -eq 10) {
    Write-Output -InputObject 'If'
}

If

In the above example, only $y -eq 5 was True. As mentioned, since we used the -or operator, only one of those conditions needed to result in True for the condition to pass. The below example uses the -and comparison operator again; however, the end results is False, so the Else portion of the If-Else is executed.

$y = 5; $z = 3

If ($y -eq 5 -and $z -eq 2) {
    Write-Output -InputObject 'If'
} Else {
    Write-Output -InputObject 'Else'
}

Else

Pretty straightforward. Let’s modify the above examples and make our Else, and ElseIf. When this example executes, the If portion will be False ($z was not assigned a numeric value of 2), so the ElseIf condition will be checked. This will result in True, as $z was assigned a numeric value of 3.

$y = 5; $z = 3

If ($y -eq 5 -and $z -eq 2) {
    Write-Output -InputObject 'If'
} ElseIf ($y -eq 5 -and $z -eq 3) {
    Write-Output -InputObject 'ElseIf'
}

ElseIf

In our final example we’ll include two ElseIf conditions. Notice in this example, that once the first one results in True, we exit the construct. That final ElseIf, while it would have also resulted in True, isn’t even considered. While we won’t go into it for now, you can nest language constructs. This is to say, we could’ve added another If statement inside the action portion of the ElseIf, and tested for $z -eq 3.

$y = 5; $z = 3

If ($y -eq 5 -and $z -eq 2) {
    Write-Output -InputObject 'If'
} ElseIf ($y -eq 5) {
    Write-Output -InputObject 'ElseIf 1' # Exits If-ElseIf.
} ElseIf ($z -eq 3) {
    Write-Output -InputObject 'ElseIf 2'
}

ElseIf 1

We’re going to end here with the If language construct, and start fresh with the Switch statement next Monday. I encourage you to ask any questions you might have about the If statement, as it’s vital you have a good understanding of this introductory language command.

Keep in mind the examples could’ve been much different than just comparing numbers. We could have return services and taken action based on whether a service was located, or not, or running or stopped. We could have returned a specific Active Directory user and taken action based on whether we found the user, or not. The list goes on.

PSMonday #29: November 14, 2016

Topic: If, If-Else, If-ElseIf II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Let’s start by discussing the fact that we can reverse the way an If statement works. Last week, we discussed that we take a specific action(s) when conditions result in true, such as in the below, conceptual example.

If (<condition>) {
    <action>
}

This can be changed for the times it’s necessary. In the next example, we’ll complete the action if the condition is false — if it’s not true. The Not logical operator negates whatever follows it. Only use the Not operator when it’s absolutely necessary. If it’s not necessary, then there’s no reason to make your conditionals any more difficult to think through.

If (-Not(<condition>)) {
    <action>
}

The below examples help show how the Not logical operator changes the condition, and therefore, the action. In the first below example, the If statement will output the word “If,” because $true evaluates to True.

If ($true) {'If'} Else {'Else'}
If

In the next example, we negate $true, making it $false, so “Else” will be written to the screen.

If (-Not($true)) {'If'} Else {'Else'}
Else

In the next example, it’ll write “If” again. You can actually walk backwards through the conditions, saying it aloud: “True, becomes False, becomes True. It’ll write If.” See if you can do that with the last two examples. While these may be helpful for learning, there likely won’t ever be a time you’re negating a Not logical operator.

If (-Not(-Not($true))) {'If'} Else {'Else'}
If

If (-Not(-Not(-Not($true)))) {'If'} Else {'Else'}

If (-Not(-Not(-Not(-Not(-Not(-Not($true))))))) {'If'} Else {'Else'}

In closing, we’ll take a look at a final example. On the first line in the below example, we assign the variable x a value of 9. When we only put $x inside the If statement’s condition, it only evaluates whether or not the variable x exists. It pays no attention to the value that’s been assign to the variable x. In the If statement following that one, we evaluate the value assigned to the variable x. If that value is equal to 9, and it is, we’ll write the word  “If” to the screen.

$x = 9

If ($x) {
    Write-Output -InputObject 'If'
}
If

If ($x -eq 9) {
    Write-Output -InputObject 'If'
}
If

We’ll close up the If topic next week. Please let me know if there are any questions on today’s PSMonday.