Join Me in a Few String Methods Using PowerShell

Join Me in a Few String Methods Using PowerShell

  • Comments 7
  • Likes

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using the String class of the Join method in Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. This morning while I was eating breakfast and reviewing my email on my Surface 2 Pro, I noticed that I have meetings all afternoon. Luckily, I was up early, and so I can get my writing done before the meetings start. The good thing is that I love meetings. Or, perhaps, I should say, that I love good meetings. Useless meetings are, well, useless.

But a good meeting is great because it lets me collaborate with brilliant people, and I always leave the meeting in a better mood than when I showed up. In fact, good meetings become the highlight of my day. Today’s meetings have the potential to be awesome, so I am looking forward to spending the afternoon collaborating with some of the brilliant people who are on my team. It will be awesome.

Using the String class static join method

The .NET Framework contains a class in the System namespace named String. The String class contains a number of methods and a few properties and other things. Complete documentation for the String Class resides on MSDN. A number of the methods of the String class are static methods. This means that they are always available, and that I do not have to create a string (an instance of the class) to gain access to the method. The Join method is one of these static methods.

Dr. Scripto says:

 Image of text

 Image of Dr. Scripto

MSDN lists five overloads for the static Join method of the System.String class. Today, I want to talk about three of these overloads. The following table explains the three ways of calling the Join method.

Method overload

Description

  Join(String, Object[])

Concatenates the elements of an object array by using the specified separator between each element.

  Join(String, String[])

Concatenates all the elements of a string array by using the specified separator between each element.

  Join(String, String[], Int32, Int32)

Concatenates the specified elements of a string array by using the specified separator between each element.

Joining objects

One of the cool things that the Join method can do is join elements of an array of objects. It also permits me to specify what I want to use as a separator between each of the elements that is joined. But beyond being cool, this element is very convenient because it lets me join the elements together without having to explicitly convert the object elements to strings. A string representation of each object in the array is automatically derived by calling the tostring() method from the object. This method works well, and it uses this type of syntax:

Method

Parameter one

Parameter two

[String]::Join(

Separator

Array of objects)

In this example, I use the Get-Process cmdlet to obtain a collection of system.diagnostics.process objects. I then display the objects and separate them by using the pipe character. The commands are:

PS C:\> $gps = Get-Process

PS C:\> [string]::Join("|",$gps)

The commands and the output associated with the commands are shown here:

Image of command output

So that is not too impressive. Beginning with Windows PowerShell 3.0, I can use the automatic foreach technique to get a single property from each object in the collection. When I use this technique, the results are much more impressive. The following command will retrieve each name of each process and join the output:

PS C:\> $gps = Get-Process

PS C:\> [string]::Join("|",$gps.name)

The command and the output are shown here:

Image of command output

Because Windows PowerShell is object oriented, and because everything is an object in Windows PowerShell, this particular overload of the Join method is one of my favorites.

Joining an array of strings

The second way to use the Join static method that I want to look at today is the one I call “Hey, let's glue together a group of strings.” Or more briefly, it is the join an array of strings method. This method is really easy to use, and it acts exactly the way I would expect it to. The following tables shows the pattern for this.

Method

Parameter one

Parameter two

[String]::Join(

Separator

Array of strings)

In this example, the first thing I need to do is to create an array of strings. After I create the array of strings, I will call the static Join method and join together the array while using a semicolon for the separator between each of the elements.

PS C:\> $arrayOfStrings = "this", "is", "an", "array", "of", "strings"

PS C:\> $separator = ";"

PS C:\> [string]::Join($separator,$arrayOfStrings)

this;is;an;array;of;strings

PS C:\>

Joining specific elements of an array of strings

One of the way cool things to do using the Join static method is to select a subset of the elements from an array of strings. The method call looks like the following:

Method

Param 1

Param 2

Param 3

Param 4

[String]::Join(

Separator

Array of strings

Start index

Count)

In the following example, I first create an array of strings and store it in a variable I call $arrayOfStrings. I next create a variable named $separator and I assign a blank space to it. Next, I create a variable named $start and a variable named $count, and I assign the value of 3 to them.

Now I call the static Join method and I specify the separator to use, the array of strings, the start index, and the count. The result is that I join the last three words from my array. This command and output are shown here:

PS C:\> $arrayOfStrings = "this", "is", "an", "array", "of", "strings"

PS C:\> $separator = " "

PS C:\> $start = 3

PS C:\> $count = 3

PS C:\> [string]::Join($separator,$arrayOfStrings, $start, $count)

array of strings

PS C:\>

That is all there is to using the String class to join strings together. String Week will continue tomorrow when I will talk about splitting strings. 

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Tooo good (Y) Well explained !

  • Hi. Thanks for the information. Picked up a few things. To me it seems a bit peculiar that you don't mention or compare to the -join operator introduced in PowerShell v2.

    Your Get-Process example for joining process names could have been written like this from v3 on (I personally prefer this way):
    (Get-Process).Name -join '|'

    With v2 you could accomplish the same using either one of these methods:
    (Get-Process | %{$_.Name}) -join '|'
    (Get-Process | Select -ExpandProperty Name) -join '|'

    You mention that it can join an array of objects and that these are automatically called .ToString() on. Well, the same applies to -join. Try this:
    (Get-Process) -join ' ### '

    ... and you'll see the same results (except another separator).

    So for the most part you can use -join instead, which is more "native PowerShell". Don't you agree?

    The last example with start index and count can be accomplished with array indexing and possibly the range operator (two periods: ..):
    $ArrayOfStrings[3..5] -join ' '

    Here's a little part for extra credits where I rather than access the Name property of the object, filter out the process names from the .ToString() object text, based on the logic that it's "whatever's between parentheses" in the "stringified" object, using -replace:
    (Get-Process | %{ $_ -replace '.*\(([^)]+)\)', '$1' }) -join '|'

    Just a few thoughts. Thanks again. I hope your meetings met your expectations!

    Best regards
    Joakim Svendsen

  • @Joakim Svendsen, I talked about the -Join operator in yesterday's Hey Scripting Guy blog post: http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/15/keep-your-hands-clean-use-powershell-to-glue-strings-together.aspx

  • thank you

  • thank you

  • thanks