PowerShell String Formatting: Master the Basics

Published:21 July 2019 - 3 min. read

The string type is probably the most popular variable in PowerShell. I don’t think I’ve ever written a script that didn’t contain at least one string. Strings are great to define a simple set of characters like a computer name, path to a text file, a registry keypath, a URL and so on. Expanding variables inside of strings and using PowerShell’s string format capabilities, you can do just about anything.

String are defined by enclosing one or more characters in single or double quotes like:

$Url = 'http:\\www.bing.com'
$FilePath = 'C:\thisissomefile.txt'

Defining strings like this is straightforward but soon you’ll find yourself needing to get the value of a variable inside strings.

For example, perhaps you have a script with a ComputerName parameter and in your script, you need to concatenate a standard prefix to it like SRV- as shown below.

$ComputerName = 'URANUS'
$ComputerName = "SRV-$ComputerName"

The $ComputerName variable’s value is now SRV-URANUS but enclosing $ComputerName inside of the string with double quotes is only one way to insert variables in strings. There are a few different ways to make that happen. Let’s take a look at two examples.

Expanding Strings

The first method is one you are probably already familiar with, called expanding strings, or simply expanding variables inside of existing strings. This is the most common way of getting the value of a variable to show up in a string.

To do this requires placing the variable inside of a string with double quotes. Single quotes will not work because they treat all characters literally.

For example, maybe I need to specify the path to a file. I know the base folder path but not the actual file name just yet. I might create a variable called $FullPath and statically input the folder path, yet make the file name a variable.

PS> $FileName = 'MyFile.txt'
PS> $FullPath = "C:\Folder\subfolder\$FileName"
PS> $FullPath
C:\Folder\subfolder\MyFile.txt

What if you need to specify an object property inside of a string? This looks a little different. In this case, I need to surround the property with parentheses and prepend a dollar sign to the front. This is called a subexpression operator. This tells PowerShell to expand the value first.

PS> $File = Get-Item -Path 'C:\MyFile.txt'
PS> $FullPath = "C:\Folder\subfolder\$($File.Name)"
PS> $FullPath
C:\Folder\subfolder\MyFile.txt

Expanding string is very common but what if you have a string that is more complicated?

Using the PowerShell String Format Operator

Another way to ensure variable values are inserted into your strings is through Powershell’s format operator (-f).

Using the format operator, you don’t have to place the variable or the property inside of a string surrounded by double quotes. You can create a string in single quotes and specify the variables that will go into that string outside of it as shown below.

PS> $File = Get-Item -Path 'C:\MyFile.txt'
PS> 'C:\Folder\subfolder\{0}' -f $File.Name
C:\Folder\subfolder\MyFile.txt

You can see it has the exact same effect. Although this time you didn’t have to use double quotes or worry about enclosing the object property in parentheses and another dollar sign. It looks a little cleaner but might be harder to understand. Using the format operator forces you to replace the {0} with $File.Name in your mind.

To add other variables, simply increment your labels by 1 and continue adding variables separated by a comma to the format operator. As long as the format operator’s index position matches the position in the string label you can add as many references as you’d like.

PS> $File = Get-Item -Path 'C:\MyFile.txt'
PS> $SubFolderName = 'folder1'
PS> 'C:\Folder\subfolder\{0}\{1}' -f $SubFolderName, $File.Name
C:\Folder\subfolder\folder1\MyFile.txt

When to Use the Format Operator

I usually prefer to place variables inside of the string and expand them because I don’t have to match an index with a value. However, there are exceptions, as in the case of special characters that must be escaped.

For example, let’s say you need to execute a command-line utility that requires you to pass a filename to it. This file path may contain spaces so you’ll need to enclose that reference with double quotes. Without those double quotes, utility.exe could not interpret the file argument correctly.

Utility.exe -file "C:\Program Files\SomeFolder\a subfolder here"

Now let’s say you want to do this in a PowerShell script. If you’re using expanding strings, it would look a little messy because you must use a backtick to escape the double quotes.

$FileName = 'C:\Program Files\SomeFolder\a subfolder here'
Start-Process -FilePath 'utility.exe' -Args "`"$FileName`""

Now, let’s get the same result with the format operator.

$FileName = 'C:\Program Files\SomeFolder\a subfolder here'
$Args = '"{0}"' -f $FileName
Start-Process -FilePath 'utility.exe' -Args $Args

I don’t have to use any escape characters. This may seem like a simple example but as soon as you come across large strings that require a lot of escaping you will soon see the real benefit of using the format operator!

Summary

The next time you find yourself having to substitute variables inside of a string, think about which method would be most readable. It will save you time in the long run.

For more posts related to working with strings, be sure to check out The PowerShell Substring: Finding a string inside a string and PowerShell Variables in Strings.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!