Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book's content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".
You want to place dynamic information (such as the value of another variable) in a string.
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 ----------------
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 uses the same rules that .NET string formatting does:
PS > $header = "Report for Today" PS > $myString = "{0}`n{1}" -f $header,('-' * $header.Length) PS > $myString Report for Today ----------------
For an explanation of PowerShell’s formatting operator, see Recipe 5.6. For more information about PowerShell’s escape characters, type Get-Help
about_Special_Characters
.
Recipe 5.6, “Place Formatted Information in a String”