tags:

views:

140

answers:

3

I'm using the string expansion feature to build filenames, and I don't quite understand what's going on.

consider:


$baseName = "base"
[int]$count = 1
$ext = ".ext"

$fileName = "$baseName$count$Ext"
#filename evaluates to "base1.ext" -- expected

#now the weird part -- watch for the underscore:
$fileName = "$baseName_$count$Ext"
#filename evaluates to "1.ext" -- the basename got dropped, what gives?

Just adding the underscore seems to completely throw off Powershell's groove! It's probably some weird syntax rule, but I would like to understand the rule. Can anyone help me out?

+2  A: 

Underscore is a legal character in identifiers. Thus, it's looking for a variable named $baseName_. Which doesn't exist.

Anon.
Well, I figured it was something stupid, I'm not disappointed. thanks.
JMarsch
+6  A: 

Actually what you are seeing here is a trouble in figuring out when one variable stops and the next one starts. It's trying to look for $baseName_.

The fix is to enclose the variables in brackets:

$baseName = "base" 
[int]$count = 1 
$ext = ".ext" 

$fileName = "$baseName$count$Ext" 
#filename evaluates to "base1.ext" -- expected 

#now the wierd part -- watch for the underscore: 
$fileName = "$baseName_$count$Ext" 
#filename evaluates to "1.ext" -- the basename got dropped, what gives?

$fileName = "${baseName}_${count}${Ext}" 
# now it works
$fileName

Hope this helps

Start-Automating
Yes, that helps a lot. Thank you.
JMarsch
Also works, but the bracket solution is cleaner.$fileName = "$($baseName)_$($count)$($Ext)"; $fileName
Doug Finke
+4  A: 

you can also use "$baseName`_$count$Ext"

hoge
This is my preferred workaround.
Richard Berg