How to expand variable in powershell?

后端 未结 3 1367
孤街浪徒
孤街浪徒 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:26

    I didn't find expanding expressions in PowerShell, but here's what I found.

    # Let's set some varaible
    $ComputerName = 'some-value'
    
    # Let's store this variable name
    $name = 'ComputerName'
    
    # Get value by `Get-Item`.
    (Get-Item variable:$name).Value # throws an exception for undefined variables.
    
    # Get value by `Invoke-Expression`
    Invoke-Expression "`$variable:$name"
    Invoke-Expression "`$$name"
    

    The same but for environment variables

    (Get-Item env:$name).Value # throws an exception for undefined environments.
    Invoke-Expression "`$env:$name"
    

    I prefer Get-Item as it "fails loudly".

    And Get-Item allows to use additional literals during this process, as well as Invoke-Expression.
    I.e. see the Computer literal below before the $ sign.

    $otherName = 'Name'
    
    (Get-Item variable:Computer$otherName).Value
    (Get-Item env:Computer$otherName).Value
    

提交回复
热议问题