Weird string expansion with PowerShell
I'm using the string expansion feature to build filenames, and I don't quite understand 开发者_Go百科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.
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 curly braces:
$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
you can also use "$baseName`_$count$Ext"
Underscore is a legal character in identifiers. Thus, it's looking for a variable named $baseName_
. Which doesn't exist.
精彩评论