Variables inside strings – a small gotcha…


I was working on a small piece of code the other day to generate file paths, and I was trying to create a folder name of the form “Part1_Part2″ where the parts come from variables. So my first – and as it turns out incorrect – assumptions was to do the following:

$part1 = "Part1"
$part2 = "Part2"
$folderName = "$part1_$part2"

You would think that $folderName contains “Part1_Part2″ at this point. But no, it actually contained “Part2″, having completely lost the first variable as well as the underscore!

Some further trial and error finally produced the solution. It appears that PowerShell is assuming that it is looking for a variable called “$part1_”, rather than “$part1″. The solution was to explicitly tell PowerShell to assess “$part1″:

$folderName = "$($part1)_$part2"

And now we get what we expected! Hope this small tip helps you all…

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: