Cash Talks - BS Walks RSS 2.0
 Tuesday, October 09, 2007

Powershell provides easy string expansion such as:

$Name = "Cash"
$Msg = "$Name is in the house"

Not too surprising the value of $Msg is "Cash is in the house".

However, what if I want the variable $Msg to be "$Name is in the house" and expand the variable $Name later.  For example, This can be useful for template string.

First, to get the template created you need to suppress the string expansion.

$Msg = '$Name is in the house'

Obviously the Template string has to be properly escaped and ready to evaluate.  Next you have to get Invoke-Expression to expand the variable

$Name = "Cash"
write-host Invoke-Expression ('"' + $Msg + '"')   # - Cash is in the house
$Name = "The Dog"
write-host Invoke-Expression ('"' + $Msg + '"')   # - The Dog is in the house

The explanation is ('"' + $Msg + '"') builds out a string with quotes on both sides ready to be evaluated by Invoke-Expression.

UPDATE

I got slapped down within hours of my first blog posts by The Man.  I'll elevate his comment into my post:

While this technique will work, it's not recommended because of the problem of nested quotes. For example, if your template string was '"$name" is in the house', then you would get an error. PowerShell provides a .NET method to do this directly which is also available to scripts. Here's an example of how to use it:

PS (109) $template = '"$name" is in the house'
PS (110) $name = "Cash"
PS (111) $ExecutionContext.InvokeCommand.ExpandString($template)
Cash is in the house
PS (112) $name = "The dog"
PS (113) $ExecutionContext.InvokeCommand.ExpandString($template)
The dog is in the house

-bruce

=========================================================
Bruce Payette
Principal Developer, Windows PowerShell Team
Microsoft Corporation

Tuesday, October 09, 2007 1:50:06 PM (Central Daylight Time, UTC-05:00)  #    Comments [2] - Trackback
Powershell
Archive
<October 2007>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Cash Foley
Sign In
Statistics
Total Posts: 17
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2010, Cash Foley
DasBlog theme 'Business' created by Christoph De Baene (delarou)