Tag Archives: PSMonday

PSMonday #28: November 7, 2016

Topic: If, If-Else, If-ElseIf

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.

Time to start learning, or reviewing, those language constructs — those “language commands,” as is the term used in the If statement’s, about topic help file. This file can be read by using the below command.

Get-Help -Name about_If

The If statement is typically the introductory control structure that someone encounters when they begin with a programming, or scripting, language. It is also the one people likely think of first when they need to start checking conditions and taking appropriate actions.

Here’s the basic, PowerShell If structure. We check a condition, and if it’s true, then we take the included action, or actions.

If (<condition>) {
    <action>
}

There are several variations of the If statement: Here’s the If-Else. This is much like the If, except that if the condition results in false, it would complete action2 instead of exiting the construct and ultimately doing nothing. Had the condition been true, it would’ve completed action1, as we saw in the first example.

If (<condition>) {
    <action>
} Else {
    <action2>
}

Here’s the If-ElseIf. The way this works is if condition1 is false, it will try condition2. If that’s true, it’ll run action2, but if it’s false, it’ll exit and take no action.

If (<condition1>) {
     <action1>
} ElseIf (<condition2>) {
    <action2>
}

If-ElseIf-Else is just like the above example; however, if condition2 resulted in false, it would complete action3 as the default action.

If (<condition1>) {
    <action1>
} ElseIf (<condition2>) {
    <action2>
} Else {
    <action3>
}

There’s really no limit to how many ElseIfs you include. Just keep in mind that Else completes a default action, as there’s no condition to check, while ElseIf requires a condition be checked (and be true), before the listed action is completed.

On a final note, if you’re going past three levels in your If constructs, then you may want to use the Switch statement. We’ll get to that one once we’ve completely knocked out the If.

PSMonday #27: October 31, 2016

Topic: Introduction to the Language Constructs

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’ve long had this feeling that people that learn and use PowerShell don’t really ever get  a fair opportunity, to learn the language constructs. Instead, they just learn them as necessary. In an effort to correct this, I believe we should spend some time in the coming weeks, covering each of them.

Well then, what’s a language construct, right? Well, it’s a control structure, of course. Okay, well then what’s that?

Within a language — PowerShell in our instance — we have to have a way to handle conditional situations, in order to take appropriate action(s). Language constructs are the If statement and its variations, it’s the switch statement, it’s the foreach loop and ForEach-Object, the for, the Do variations, and the While loop, too.

In the coming weeks, we’ll spend some time with each of the constructs, so that you’ve seen and used them all, or simply reviewed them, if you’ve used them before. Knowing which to use when, is a vital skill, and best left to second nature once you’ve had experience with them all. I’ll be sure to include some of the times you might choose one over the other, when you can do the same thing with more than just one of the constructs. We’ll start next Monday with If, If-Else, and If-ElseIf.

PSMonday #26: October 24, 2016

Topic: PowerShell’s Importance

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.

Today is the 26th PowerShell Monday. That means I’ve been writing these for a full half year.

I want to use this morning to point some things out. If you take the time to study each of these emails, then you’re going to be better at your job, where PowerShell can be utilized, in just a year’s time. Take the time to read these whether you already know the content, or not. Now, in conjunction, it’s important to practice what you’re reading, too. Do things in the GUI and then consider how you might complete the same task at the ConsoleHost. Ask questions if you have them, as I’m always willing to help.

I learned early on that PowerShell is going to be a requirement for Windows systems administration. Microsoft keeps proving this, as do other companies that are using it in conjunction with their own products. The inventor of PowerShell is now a Microsoft Technical Fellow — that’s the highest technical title one can receive from Microsoft. He’s the lead architect for the Enterprise Cloud Group and the Microsoft Azure Stack. He presides over Windows Server and the System Center products. Don’t think for a moment that PowerShell won’t continue to play a part at Microsoft. You’re going to need this skill. Keep in mind that we’re not going to need a bunch of click-next admins, as they’re called, in the coming years.

After writing a PSMonday each week for a half of a year, I plan to place the first 26 weeks’ worth of content into a single PDF and distribute that in the coming weeks. If you haven’t read all of them, then this might be a nice way to do that.

On a final note, PowerShell was recently introduced on Linux and Mac. My first thought was, great, soon Windows administrators can support Linux, too. It was after a recent trip to Phoenix for a PowerShell Saturday event, however, where Jason Helmick — a PowerShell MVP — made an interesting point: Linux administrators are going to be able to support Windows, too. It’s time to learn PowerShell, and maybe more about both operating systems. In fact, Jason told a room full of Windows administrators, the same thing.

PSMonday #25: October 17, 2016

Topic: $PSDefaultParameterValues 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.

To recap last week, the $PSDefaultParameterValues preference variable stores default parameter names and corresponding values for cmdlets and functions. This means we can use cmdlets and functions with modified parameters, without the need to type in the names and values each time.

Last week we used the Add and Remove methods. This week, we’ll use standard hash table syntax, since that’s all this variable holds. Hash tables were first introduced back on May 30, 2016 when we first discussed creating and splatting a parameter hash table. A hash table contains key-value pairs.

Let’s add a new entry to our empty $PSDefaultParameterValues variable.

$PSDefaultParameterValues = @{'Get-Help:ShowWindow'=$true}
$PSDefaultParameterValues

Name                           Value
----                           -----
Get-Help:ShowWindow            True

Just as we did last, when we enter the variable name after it’s populated, it’ll return the results in the standard, hash table output to include the Name and Value properties.

With the ShowWindow parameter name set to a value of True, Get-Help will always show the full help inside a GUI window and not pollute the ConsoleHost or ISE (PowerShell 3.0 and greater only), without the need to actually type the switch parameter -ShowWindow.

If your variable is already holding a value, be sure to use the += assignment operator instead of the = assignment operator, or you’ll overwrite what was already being stored in the variable.

On an entry after the first one, use this:

$PSDefaultParameterValues += @{'Get*:Verbose'=$true}

Not this:

$PSDefaultParameterValues = @{'Get*:Verbose'=$true}

Notice that in the above examples we’ve used a wildcard character. If this is added to your $PSDefaultParameterValues, then all Get-* cmdlets and functions will include the Verbose parameter.

PSMonday #24: October 10, 2016

Topic: $PSDefaultParameterValues

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 some understanding about commands, cmdlets, functions, and parameters, we can start to discuss the $PSDefaultParameterValues preference variable. This variable allows you to specify default parameter values for cmdlet or function parameters.

This is to say, that you can ensure a specific parameter value is always used for a specific parameter name, for a specific cmdlet or function, even when you don’t explicitly include them. Let’s say you use the Get-ADComputer cmdlet and you always want to use the DC01 Domain Controller to perform the lookup. That’s probably not the best idea, but without $PSDefaultParameterValues, you’d have to type the parameter each time.

Get-ADComputer -Identity membersrv05 -Server DC01

If we defined a default parameter value, we could drop the -Server DC01 from the command and it would still be included. There’s a couple different ways to add an entry to $PSDefaultParameterValues. We’ll use the Add method this week.

$PSDefaultParameterValues.Add('Get-ADComputer:Server','DC01')
$PSDefaultParameterValues

Name                           Value
----                           -----
Get-ADComputer:Server          DC01

Again, with this value set, the command below would still be certain to use DC01.

Get-ADComputer -Identity membersrv05

While we’re here, let’s also look at the Remove method. This is how we’d remove an already existing entry in the $PSDefaultParameterValues variable.

$PSDefaultParameterValues.Remove('Get-ADComputer:Server')

All gone, and all done. We’ll discuss this topic some more next Monday.

PSMonday #23: October 3, 2016

 Topic: Commands, Cmdlets, and Functions

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.

Before we jump into the next topic, I think it would be wise to ensure we discuss the differences between commands, cmdlets, and functions. In doing that, we’ll also learn, or clarify, the differences between parameters, parameter names, and parameter values.

As we’ve learned, in a roundabout way, cmdlets and functions have the potential to include parameters. Scripts in fact, can also include parameters. A parameter is made up of a parameter name and a parameter value, or values.

A cmdlet, such as Get-Service, Stop-Process, Get-EC2Instance, and Set-ADUser, is likely written in C#, and is compiled code. A function, which can be written in a simple text editor, isn’t compiled, as the source can be easily read. These include Get-Volume, Get-Verb, New-SmbShare, and many more, including those we might write ourselves using the ISE, or Visual Studio Code. Those products are both better alternatives to using a simple text editor.

Let’s take a look at a command, break down each part, and then call it a day.

Get-EventLog -ComputerName DC01,DC02 -LogName Application -Verbose

Get-EventLog
This is the command. The term command can be used for just the cmdlet or function, or a cmdlet or function that includes parameters. You might also just call it by its CommandType: cmdlet or function. I’m not completely sure if it’s been mentioned before or not, but cmdlet is pronounced command-let.

-ComputerName DC01,DC02
This is a parameter.

-ComputerName
This is the parameter name.

DC01,DC02
These are the parameter values.

-LogName Application
This is also a parameter.

-LogName
This is the parameter name.

Application
This is the parameter value.

-Verbose
Even this, is a parameter.

Before we wrap up, I want to quickly discuss the last parameter mentioned: Verbose. There are parameter names that don’t require any specified parameter value be included. These are called switch parameters. If they’re included, their parameter value — even though you can’t see it — is True ($true), and if they’re not included, their parameter value is False ($false). Therefore, their default value is always $false.

Alright, back with more next time.

PSMonday #22: September 26, 2016

Topic: Get-Member Continued 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.

Now that we’ve had a brief introduction to arrays, let’s quickly get back and discuss the difference of piping to Get-Member, and not piping to Get-Member. Let’s begin by creating a new array, but this time, we’ll make sure it’s holding both string and integer values.

$array = 1,'string1',2,'string2'
$array

1
String1
2
String2

Let’s pipe this to Get-Member. I’ve modified the below command, so it takes up less space; I’m only returning the TypeName. I’ve also included the -Unique parameter as a part of the Select-Object command. Without it, it would return the TypeName for each of the properties and methods. Try it without, and see what I mean.

$array | Get-Member | Select-Object TypeName -Unique

TypeName
--------
System.Int32
System.String

When we pipe to Get-Member, we get a result for each of the different types of objects in the array. Although our array has four total values, there’s still only two different types of objects: integer and string.

Let’s set up the next command, but this time we’ll use Get-Member without piping.

Get-Member -InputObject $array | Select-Object TypeName -Unique

TypeName
--------
System.Object[]

Notice that there’s nothing about integers or strings. In this next example, we’ll apply one of the methods. I happen to know there’s a method called GetType that will provide a bit more information about our $array variable. If you didn’t know about the GetType method, you could’ve removed the pipe and Select-Object command, to see all of the available properties and methods, and tested some out.

(Get-Member -InputObject $array).GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     Object[]              System.Array

Based on the above results, you can see that PowerShell knows that this is an array. So what’s all this mean? It means that when we don’t pipe to Get-Member, we evaluated the variable as a whole — whatever it might be. When we pipe to Get-Member, we’re evaluating the type of each element contained in the array, or rather, each object in a collection.

The pipeline in PowerShell is used for much more than Get-Member, but the concept is the same. Each object has a turn to go across, or through, the pipeline, in order to be evaluated. This is a key concept and I’m sure we’ll see it in the future, in topics unrelated to the Get-Member cmdlet.

PSMonday #21: Monday, September 19, 2016

Topic: Get-Member Continued III (and Arrays)

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.

At this point, we’ve only ever piped to the Get-Member cmdlet, but there’s times we might want to use the cmdlet differently. Before we continue, we need to understand arrays, and so we’re going to break off from Get-Member this week.

In our previous examples, we’ve typically only assigned a single value to a variable.

$a = 'dog'
$a

dog

Using an array allows us to assign multiple values to a single variable. Here’s how we do that, and how it appears when we return the variable’s newly assigned values.

$b = 'dog','cat','bird','frog'
$b

dog
cat
bird
frog

You may see arrays created using the array operator syntax, as well: @().

$b = @('dog','cat','bird','frog')

We can access each of the values in the array variable using an index. This is the position of a value within the array. Arrays are always zero-based, so the first value in the array is always at index 0.

$b[0]

dog

Now let’s return all four values. We’ll do them out of order, so you can see that the indexes really do, return the proper value in the array.

$b[3] # 4th value.
$b[0] # 1st value.
$b[2] # 3rd value.
$b[1] # 2nd value.

frog
dog
bird
cat

We’ve learned that the array index 0 and then higher, each represent the next value in the array. We can also move backwards through an array, using negative indexes. Here’s both.

$b[0]
$b[1]
$b[2]
$b[3]
'--------'
$b[-1]
$b[-2]
$b[-3]
$b[-4]

dog
cat
bird
frog
--------
frog
bird
cat
dog

This means that index [-1] is always the last value in an array, just like index [0] will always be the first. Knowing this may come in handy one day; it was for me. Next Monday, we’ll actually get back to Get-Member, now that we have some basic understanding of arrays, if you didn’t have them already.

PSMonday #20: Monday, September 12, 2016

Topic: Get-Member Continued 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 to Get-Member and some experimentation with a few methods. We’ll start by using a method that I didn’t include in my shortened results last week: PadLeft. The PadLeft method will add spaces, by default, to the left side of a string. Remember, “methods are things the object can do.”

$x = '5' + '5'
$x

55

$x.PadLeft(5)

   55

A little boring, so let’s pad it with asterisks instead.

$x.PadLeft(5,'*')

***55

You might have expected to see five asterisks. Nope. The PadLeft method indicates that any space to the left of the existing string be padded up to five total spaces, to include the string itself. So, how might we ensure there’s five asterisks before the string, if that’s what we had really wanted? Think back to the string’s length from last week. Here’s that example again.

$x.Length

2

In the next example, we’ll add five to the length (two), in order to ensure we end up with five, actual asterisks.

$x.PadLeft(5 + $x.Length,'*')

*****55

Here’s another example with a different string and method. This uses the Split method to split a string on the space between each word.

"Today is everyone's favorite day!".Split(' ')

Today
is
everyone's
favorite
day!

I should mention that the above, split example should’ve been written like it is below. The default split character is the space; it doesn’t need to be included. Now, if we had opted to split on a different character, word, or combination thereof, that would’ve needed to be included inside the single quotes.

"Today is everyone's favorite day!".Split()

We’ll stop here for now and pick it up next Monday.

PSMonday #19: Monday, September 5, 2016

Topic: Get-Member Continued

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.

If nearly everything in PowerShell is an object, then let’s look at two of the members — properties and methods — of our two results, ’55’ and 10. Typically, we pipe to Get-Member. In the first example, we’ll recreate our string value of ’55’ and see what we can learn about it.

$x = '5' + '5'
$x

55

$x | Get-Member

  TypeName: System.String

In the above results, I’ve included only the TypeName of the object for now, and haven’t yet included all the properties and methods returned by Get-Member, that we’ll see momentarily. The TypeName indicates that the object is a string object.

In the more complete, Get-Member results, I’ve included the first several methods and the one and only property. As the value in $x is a string, there’s not much to it, property wise. In this case, there’s just a length property. In the below results, I haven’t include the Definition property. If you run these commands yourself, don’t be surprised to see a third property, or column, included.

  TypeName: System.String

Name             MemberType
----             ----------
Clone            Method
CompareTo        Method
Contains         Method
CopyTo           Method
EndsWith         Method
Equals           Method
GetEnumerator    Method
GetHashCode      Method
...
Length           Property

Let’s return the length property to see the length of the string stored in the variable $x. The value is ’55’, so a length of two would make sense. Let’s double-check.

$x.Length

2

Let’s recreate our numeric value of 55, as well, and pipe it to Get-Member.

$y = 5 + 5
$y

10

$y | Get-Member

  TypeName: System.Int32

Name           MemberType
----           ----------
CompareTo      Method
Equals         Method
GetHashCode    Method
GetType        Method
GetTypeCode    Method
ToBoolean      Method
ToByte         Method
ToChar         Method
ToDateTime     Method
ToDecimal      Method
ToDouble       Method
ToInt16        Method
ToInt32        Method
ToInt64        Method
ToSByte        Method
ToSingle       Method
ToString       Method
ToType         Method
ToUInt16       Method
ToUInt32       Method
ToUInt64       Method

The variable $y is storing an integer object, and according to Get-Member, doesn’t include any properties. That’s a good start for this holiday Monday. Next week, we’ll start working with some of the different methods.