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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With