Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand variable in powershell?

Tags:

powershell

Get-WmiObject -Class win32_logicaldisk -Filter 'DeviceID="C:"'

does what I want,

$var="C:"
Get-WmiObject -Class win32_logicaldisk -Filter 'DeviceID="{$var}"'

does nothing. I tried to change the quotes, to concatenate strings, and other 1000 things, but they didn't work. Why the above example doesn't work, and what would work?

like image 752
Andrei Avatar asked Dec 01 '16 16:12

Andrei


1 Answers

When you start a string literal with ' (single-quotes), you're creating a verbatim string - that is, every character inside the string is interpreted literally and variable references and expressions won't expand!

Use " if you want the variable to be expanded:

$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='$var'"

If your variable name has weird characters, or is followed by a word character, you can qualify the variable name with curly brackets {} immediately after the $:

$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='${var}'"
like image 57
Mathias R. Jessen Avatar answered Oct 27 '22 22:10

Mathias R. Jessen