How to expand variable in powershell?

后端 未结 3 1334
孤街浪徒
孤街浪徒 2021-01-06 02:35
Get-WmiObject -Class win32_logicaldisk -Filter \'DeviceID=\"C:\"\'

does what I want,

$var=\"C:\"
Get-WmiObject -Class win32_logical         


        
3条回答
  •  再見小時候
    2021-01-06 03:08

    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}'"
    

提交回复
热议问题