Insert Dynamic Information in a String

1. Problem

You want to place dynamic information (such as the value of another variable) in a string.

2. 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
        ----------------



3. 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
        ----------------
Tags: , , , , , , ,