Monthly Archive

Categories

String expansion

One of the nice features of PowerShell is string expansion.  Put a variable in the middle of a double quoted string (single quoted strings take the contents literally and don't expand) and the variable is substituted into the string when it is evaluate.

Example

PS> $a = "a"
PS> $b = "b"
PS> $c = "c"

PS> "$a"
a

PS> "$a$b$c"
abc

Define three string variables as shown and then try substituting them into the string.  It works as shown. This seems to break down when an underscore character gets involved.

PS> "$a_"

PS> "$a$b"
ab
PS> "$a$b_"
a
PS> "$a_$b"
b
PS> "_$a$b"
_ab
PS> "_$a$b$c"
_abc
PS> "$a_$b$c"
bc
PS> "$a$b_$c"
ac
PS> "$a$b$c_"
ab
PS> "_$a$b$c"
_abc

Put the underscore character after the variable and the variable is ignored. Put it before a variable and it works.

Use an escape character

PS> "$a`_$b"
a_b
PS>

and it works.

So the underscore character has the effect of nullifying a variable.  I've not seen this before and if anyone has an explanation I'd love to hear it.  I've not been able to find an explanation by checking out the usual sources. Maybe I'm missing something here but in the mean time be careful when using _ characters like this.

 

Share this post :

Technorati Tags: PowerShell

Leave a Reply