Variable Expansion in PowerShell Expressions

Variable Expansion in PowerShell Expressions

Q: I'm writing some scripts in Windows PowerShell, but the variables I created aren't working as I expect in other strings--why?
A:
When you create a variable such as $var, the way PowerShell knows it's a variable is the fact it starts with the dollar sign.

In some circumstances, PowerShell can even automatically translate the variable into its actual value as part of another string. For example, I could input the following:

$var = "John"
write-host "Hello $var"

Hello John

But if I try a single quote it doesn't work:

$var = "John"
write-host 'Hello $var'

Hello $var

So, the first important point is, double-quoted strings expand environment variables, single-quoted strings do not.

You can always use PowerShell commands such as -join, or just concatenate strings by using +=. I can even use the following:

$var = "John"
$var2 = "Savill"
"Hello {0} {1}" -f $var,$var2

The problem is even bigger if the value of your variable is an object that has its own attributes, for example:

$notepadproc = get-process notepad
write-host "The process ID of Notepad is $notepadproc.Id"
The process ID of Notepad is System.Diagnostics.Process (notepad).Id

This is clearly not what I wanted. The problem is only the variable gets expanded in a string, not property extensions, which is why anything after the variable name is just output as part of the string.

The solution is to put the whole expression into brackets. For example:

$notepadproc = get-process notepad
write-host "The process ID of Notepad is $($notepadproc.Id)"

The process ID of Notepad is 4640

I hope this helps clear things up.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish