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.

Leave a Reply

Your email address will not be published. Required fields are marked *