Thursday, July 19, 2012

Variables in PowerShell Strings

One of the amazing things about PowerShell compared to other scripting languages (VBScript) is its ability to resolve variables within strings.  ( variable expansion, this new feature looks to make concatenation a thing of the past.  Furthermore, with PowerShell's handling of double versus single quotes, there will no longer be cases of writing four quotes just to get one (escaping a quote with a quote).

However, one thing tripped me up for the last year, until I learned the answer from training with Ashley McGlone. (  The variable expansion didn't help when accessing a property or method of an object, or item in an array.  So I would have a lot of "$a" + $b.toString() + "c" for example.  Then, he showed me the secret:

In a string, I can use $(), and put whatever code I want into it, even an if statement or code block!  So the previous example becomes "$a$($b.toString())c", which is much more compact.  Furthermore, PS3 ISE will color the items in parentheses as variables and members instead of red like strings, making it easier to see what is going on inside them.

One more reason I really enjoy PowerShell!

No comments:

Post a Comment