Powershell Variables and the Underscore character

Well you learn something new every day …

The underscore character _ is a valid character in a variable name in Powershell.

You will find this out if you try and concatenate two variables separated by an _ to make a string value for say a file name e.g.

$filename = “$name_$time”

Even if you have previously correctly defined values for $name and $time, Powershell will be looking for a variable called $name_ which will most likely be undefined and the result will be just

$filename = “$time”

The solutions are:

$filename = “$name`_$time”   # escape the _ with `

or

$filename = “${name}_$time”   # use curly braces to delimit the variable name

Some great explanations of this in the following references:

http://richbrownesq-sqlserver.blogspot.com.au/2012/07/powershell-string-concatenation-with.html

https://www.vistax64.com/powershell/274848-variable-string-surrounded-underscore.html

http://www.techtalkz.com/microsoft-windows-powershell/448406-underscores.html

https://msdn.microsoft.com/en-us/powershell/reference/3.0/microsoft.powershell.core/about/about_variables

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

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