PowerTip: Include Expressions in a String in PowerShell

PowerTip: Include Expressions in a String in PowerShell

  • Comments 3
  • Likes

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.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • There is a typo in "The ${$p.Name} process uses the ${$p.StartInfo.WindowStyle} window style." It should use parenthesis instead as "The $($p.name) process uses the $($p.StartInfo.WindowStyle) window style."

  • Useful.

  • Thanks, Larry! We'll fix it!