Behind the PowerShell Pipeline logo

Behind the PowerShell Pipeline

Subscribe
Archives
December 10, 2024

Putting It Together in PowerShell

It should come as no surprise that we often use PowerShell to build things, and I mean more than custom object output. We often need to build strings, arrays, and hash tables. We also need to manipulate dates and times. Very often we are building these things up in layers. I thought I would take a moment to look at some of the ways we can put these things together in PowerShell.

One thing to keep in mind is when you need to add things together. Do you have all of the elements you need or will you be processing and adding things as you go? This can make a difference in how you approach the problem.

Hashtable Additions

Let's start out with looking at adding to a hashtable.

$user = @{
    Name  = 'Roy G. Biv'
    Title = 'Active Directory Administrator'
    City  = 'Green Bay'
    State = 'WI'
}

Using the Add Method

Perhaps later in your code you need to add a name value pair to the hashtable. You can do this by using the Add() method.

$user.Add("Department", "IT Services")

The Add() method takes parameters for the key, Department, and the value, IT Services.

PS C:\> $user

Name                           Value
----                           -----
Department                     IT Services
Title                          Active Directory Administrator
City                           Green Bay
Name                           Roy G. Biv
State                          WI

Using the Add() method makes it clear that you are adding a new key value pair to the hashtable.

Indirect Addition

However, you can also add a new key value pair to a hashtable by simply assigning a value to a key that does not exist.

$user['FirstName'] = $user.Name.Split()[0]
$user['LastName']  = $user.Name.Split()[-1]

Normally, you can use this technique to update an existing key value pair. But if the key does not exist, PowerShell will add it to the hashtable.

PS C:\> $user

Name                           Value
----                           -----
City                           Green Bay
Department                     IT Services
Name                           Roy G. Biv
LastName                       Biv
State                          WI
Title                          Active Directory Administrator
FirstName                      Roy

These techniques can be used to build up a hashtable as you go.

Arrays

Arrays are a bit different.

$a = @('apple', 'banana', 'cherry', 'date', 'elderberry')

You can't add to an array in the same way you can add to a hashtable. You can't use the Add() method on an array, even though the underlying object contains an Add() method.

PS C:\> $a -is [Array]
True
PS C:\> $a.PSBase | Get-Member Add

   TypeName: System.Management.Automation.PSMemberSet

Name MemberType Definition
---- ---------- ----------
Add  Method     int IList.Add(System.Object value)

PS C:\> $a.add("Frank")
MethodInvocationException: Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."

Instead, use the += operator to add to an array.

$a+="Frank"
$a+="Grace","Henry","Irene","Jack"

The operator appends items to the array.

PS C:\> $a
Alice
Bob
Carol
David
Emily
Frank
Grace
Henry
Irene
Jack

Technically, there are implications to using the += operator. It creates a new array and copies the old array to the new array. This can be a performance issue if you are adding a lot of items to a very large array. But for most cases, it is not a problem and I seem to recall a fix for this in a recent version of PowerShell 7. The array syntax I'm demonstrating is very common in PowerShell scripting.

Joining

Another useful building technique is to join elements together, typically strings, or items that can be treated as strings. Here's a variable with an array of names.

$names = 'Alice', 'Bob', 'Carol', 'David', 'Emily'

You might want to display the names in a message.

PS C:\> Write-Host "Creating accounts for $names"
Creating accounts for Alice Bob Carol David Emily

Let's clean this up using the -join operator.

PS C:\> $list = $names -join ','
PS C:\> Write-Host "Creating accounts for $list"
Creating accounts for Alice,Bob,Carol,David,Emily

The -join operator joins the elements of an array into a single string. You can specify a delimiter, in this case, a comma. If you don't need a delimiter, you can write an expression with the -join operator at the beginning of the PowerShell expression.

PS C:\> -join $names
AliceBobCarolDavidEmily

It feels a little odd to see the -join operator at the beginning of the expression, but it works.

String Addition

Next, let's turn our attention to strings. I'm going to skip covering the .NET System.Text.StringBuilder class because I think it is overkill for most PowerShell scripting. Instead, I'll show you how to build strings in PowerShell.

You might be tempted to use the + operator to add to a string.

$s = '[' + (Get-Date).TimeOfDay + '] Starting the update process on ' + $env:COMPUTERNAME

I see code like this very often from PowerShell beginners. This is the technique we used back in the VBScript days.

Want to read the full issue?
GitHub Bluesky LinkedIn About Jeff
Powered by Buttondown, the easiest way to start and grow your newsletter.