Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird string expansion with powershell

Tags:

powershell

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?

like image 620
JMarsch Avatar asked Jan 19 '10 22:01

JMarsch


1 Answers

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

like image 153
Start-Automating Avatar answered Oct 07 '22 02:10

Start-Automating