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 `


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

Some great explanations of this in the following references:






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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s