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