Learn the PowerShell string format and expanding strings

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is a task automation and configuration management framework from Microsoft. Strings in PowerShell are delineated by quotation marks around the text that makes up the string, then followed by indented blocks containing run commands or other strings to be executed when there’s nothing else on the line.

The “powershell string concatenation” is a command that allows users to combine strings of text. This can be done by using the “+” operator, or through the use of the “concat()” function in PowerShell.

Learn the PowerShell string format and expanding strings

In PowerShell, the string type is perhaps the most often used variable. I don’t believe I’ve ever created a script without at least one string in it. Strings are useful for defining a basic collection of characters, such as a machine name, a text file path, a registry keypath, or a URL. You can accomplish almost anything using PowerShell’s string format features including expanding variables inside of strings.

Strings are made up of one or more characters encased in single or double quotations, as in:

‘http:www.bing.com’ as $Url $FilePath = ‘C:thisissomefile.txt’; $FilePath = ‘C:thisissomefile.txt’; $FilePa

It’s simple to define strings like this, but you’ll quickly find yourself wanting to access the value of a variable contained inside strings.

For instance, suppose you have a script with a ComputerName parameter, and you need to append a standard prefix to it, such as SRV-, as seen below.

$ComputerName = “SRV-$ComputerName” $ComputerName = “URANUS”

The value of the $ComputerName variable is now SRV-URANUS, but using double quotes to enclose $ComputerName within a string isn’t the only option to place variables in strings. There are a few options for doing this. Let’s look at a few of instances.

Strings Expansion

The first method is one you are probably already familiar with, called Strings Expansion, 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 so, wrap the variable in double quotes and place it within a string. Because single quotes take all characters literally, they will not function.

For instance, I may need to indicate the location of a file. I know the location to the root folder, but not the file name. I could build a variable named $FullPath and statically enter the folder path while keeping the file name variable.

PS> $FileName = ‘MyFile.txt’ PS> $FullPath = “C:Foldersubfolder$FileName” PS> $FullPath C:FoldersubfolderMyFile.txt

What if you need to use a string to indicate an object property? This seems to be unique. In this scenario, I need to put parenthesis around the property and add a dollar symbol to the front. A subexpression operator is what it’s called. This instructs PowerShell to first expand the value.

PS> $File = Get-Item -Path ‘C:MyFile.txt’ PS> $FullPath = “C:Foldersubfolder$($File.Name)” PS> $FullPath C:FoldersubfolderMyFile.txt

It’s fairly normal to expand a string, but what if your string is more complicated?

Using the String Format Operator in PowerShell

The format operator in Powershell is another approach to guarantee variable values are incorporated into your strings (-f).

You don’t have to put the variable or property within a string enclosed by double quotes if you use the format operator. As demonstrated below, you can build a string in single quotes and describe the variables that will go into it outside of it.

PS> $File = Get-Item -Path ‘C:MyFile.txt’ PS> ‘C:Foldersubfolder{0}’ -f $File.Name C:FoldersubfolderMyFile.txt

It has the same effect, as you can see. You didn’t have to use double quotes this time, and you didn’t have to worry about surrounding the object property in parenthesis and another dollar sign. It seems to be cleaner, yet it may be more difficult to comprehend. When you use the format operator, you must replace the 0 with $File. Make a mental note of it.

To add more variables, just increase the value of your labels by one and continue adding variables to the format operator separated by a comma. You may include as many references as you like as long as the index position of the format operator matches the position in the string label.

PS> $File = Get-Item -Path ‘C:MyFile.txt’ PS> $SubFolderName = ‘folder1’ PS> ‘C:Foldersubfolder{0}{1}’ -f $SubFolderName, $File.Name C:Foldersubfolderfolder1MyFile.txt

When Should the Format Operator Be Used?

Because I don’t have to match an index with a value, I normally prefer to add variables within the text and expand them. There are, however, certain exceptions, such as special characters that must be escaped.

Let’s imagine you need to run a command-line tool that needs a filename to be passed to it. Because this file path could include spaces, you’ll need to surround it in double quotes. Utility.exe would be unable to appropriately comprehend the file parameter without the double quotes.

Utility.exe -file “C:Program FilesSomeFoldera subfolder here” Utility.exe -file “C:Program FilesSomeFoldera subfolder here”

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

Start-Process -FilePath ‘utility.exe’ -Args “‘”$FileName’”” $FileName = ‘C:Program FilesSomeFoldera subdirectory here’

Now let’s use the format operator to get the same effect.

$FileName = ‘C:Program FilesSomeFoldera subfolder here’; $FileName = ‘C:Program FilesSomeFoldera subfolder here’; $FileName = $Args = “0” -f $Args = “0” -f $Args = “0” -f $Args = “0” Start-Process $FileName -FilePath ‘utility.exe’ -Args $Args

There is no need for me to utilize any escape characters. This may seem to be a simple example, but whenever you encounter long strings that need a lot of escaping, you’ll quickly realize the true value of the format operator!

Summary

Consider which way would be the most understandable the next time you need to replace variables inside a string. In the long term, it will save you time.

Check out The PowerShell Substring: Finding a string within a string and PowerShell Variables in Strings for additional blogs on dealing with strings.

PowerShell is a command-line tool that allows users to manage and automate tasks. One of the most common tasks using PowerShell is to format strings. The “powershell format string named parameters” will teach you how to do this.

Frequently Asked Questions

How do I format a string in PowerShell?

A: The string is enclosed in double quotes. To use a single quote, precede it with the backslash character. For example for to escape the letter r in Are you ready?

How do you append strings in PowerShell?

A: Use the concatenate command, which is a combination of two words.

How do I create a multiline string in PowerShell?

A:
In PowerShell, a multiline string is created using the $… syntax. You can have many lines in your strings by separating them with one or more spaces ($This is a multi-line string). To add line breaks to your text, use any of these characters: n, \r
,\t.

Related Tags

  • powershell format string with variable
  • powershell strings
  • powershell string interpolation object property
  • powershell substring
  • powershell string format padding

Table of Content