February 15th, 2014

PowerTip: Include Expressions in a String in PowerShell

Doctor Scripto
Scripter

Summary: Learn how to include expressions in a string in Windows PowerShell.

Hey, Scripting Guy! Question How do I include expressions in a string in Windows PowerShell? They’re not replaced correctly in a
          double-quoted string:

PS C:> $p = Get-Process PowerShell
PS C:>”The $p.Name process uses the $p.StartInfo.WindowStyle window style.”

The System.Diagnostics.Process (powershell).Name process uses the
System.Diagnostics.Process (powershell).StartInfo.WindowStyle window style.

Hey, Scripting Guy! Answer Enclose the values in a new variable:

PS C:>”The $($p.Name) process uses the $($p.StartInfo.WindowStyle) window style.”
The powershell process uses the Normal window style.

         Or use a formatted string:

PS C:>”The {0} process uses the {1} window style.” -f $p.Name, $p.StartInfo.WindowStyle
The powershell process uses the Normal window style.

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.

Feedback