Problem
You want to place special characters (such as tab and newline) in a string variable.
Solution
In an expanding string, use PowerShell’s escape sequences to include special characters such as tab and newline.
PS >$myString = "Report for Today`n" PS >$myString Report for Today
Discussion
Aliteral string uses single quotes around its text, while an expanding string uses double quotes around its text.
In a literal string, all the text between the single quotes becomes part of your string. In an expanding string, PowerShell expands variable names (such as $ENV: SystemRoot) and escape sequences (such as `n) with their values (such as the SystemRoot environment variable and the newline character).
Unlike many languages that use a backslash character (\) for escape sequences, PowerShell uses a backtick (`) character. This stems from its focus on system administration, where backslashes are ubiquitous
in path names.
Insert Dynamic Information in a String in Windows PowerShell
Problem
You want to place dynamic information (such as the value of another variable) in a string.
Solution
In an expanding string, include the name of a variable in the string to insert the value of that variable.
PS >$header = "Report for Today" PS >$myString = "$header`n" PS >$myString Report for Today
To include information more complex than just the value of a variable, enclose it in a subexpression:
PS >$header = "Report for Today" PS >$myString = "$header`n$('' * $header.Length)" PS >$myString Report for Today
Discussion
Variable substitution in an expanding string is a simple enough concept, but subexpressions deserve a little clarification.
A subexpression is the dollar sign character, followed by a PowerShell command (or set of commands) contained in parentheses:
$(subexpression)
When PowerShell sees a subexpression in an expanding string, it evaluates the subexpression and places the result in the expanding string. In the solution, the expression '' * $header.Length tells PowerShell to make a line of dashes $header.Length long.
Another way to place dynamic information inside a string is to use PowerShell’s string formatting operator, which is based on the rules of the .NET string formatting:
PS >$header = "Report for Today" PS >$myString = "{0}`n{1}" f $header,('' * $header.Length)
PS >$myString Report for Today
For more information about PowerShell’s escape characters, type GetHelp About_Escape_Character or type GetHelp About_Special_ Character.