String Concatenation in PowerShell

I was watching a Pluralsight course this morning, and I came across the second instance of VBA-style string concatenation that I’d seen this week.

You know, like this:

$FirstName = "Joe"
$LastName = "Bloggs"
$DisplayName = $LastName + ", " + $FirstName
$UserName = $FirstName + "." + $LastName + ""

This is one of my pet peeves, as it’s not necessary in PowerShell, and it makes the code harder to read.

PowerShell is quite capable of expanding variables within a string. This is called an ‘expanding string’:

$DisplayName = "$LastName, $FirstName"
$UserName = "$FirstName.$"

If you want to go one step farther, you can use the format operator:

$DisplayName = "{0}, {1}" -f $LastName,$FirstName
$UserName = "{0}.{1}" -f $FirstName,$LastName

This allows for cleaner insertion of variables, especially if you want to do something like this to get rid of capital letters in an email address or UPN (another of my pet peeves):

$UserName = "{0}.{1}" -f $FirstName.ToLower(),$LastName.ToLower()

Some good reading on the Hey, Scripting Guy! blog:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s