Thursday, 19 July 2012

Powershell: String concatenation with underscore confusion

In putting together a simple powershell script to download a file and store it on a filesystem, I came across some strangeness with the user of Underscore (_) when concatenation variables. Essentially, I wanted to create a filename based upon 2 powershell variables, separated by an underscore.

I wanted my filename to be: 
And my powershell read something like:
$File = "C:\$FirstName_$LastName"

Interestingly, when run in my script the output of $File would be 

I was suspicious of the underscore and sure enough this was the causing the issue. I stumbled upon this thread on Stackoverflow which explains the issue as the underscore is a valid character in identifiers so its looking for a variable named $FirstName_.

There are 2 workarounds for this:
1) $File = "C:\$FirstName`_$LastName"
2) $File = "C:\${FirstName}_$LastName"

No comments:

Post a comment

/* add this crazy stuff in so i can use syntax highlighter