How do I get the value of a registry key and ONLY the value using powershell

前端 未结 9 577
醉酒成梦
醉酒成梦 2020-12-13 11:52

Can anyone help me pull the value of a registry key and place it into a variable in PowerShell? So far I have used Get-ItemProperty and reg query

9条回答
  •  难免孤独
    2020-12-13 12:22

    NONE of these answers work for situations where the value name contains spaces, dots, or other characters that are reserved in PowerShell. In that case you have to wrap the name in double quotes as per http://blog.danskingdom.com/accessing-powershell-variables-with-periods-in-their-name/ - for example:

    PS> Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
    
    14.0         : C:\Program Files (x86)\Microsoft Visual Studio 14.0\
    12.0         : C:\Program Files (x86)\Microsoft Visual Studio 12.0\
    11.0         : C:\Program Files (x86)\Microsoft Visual Studio 11.0\
    15.0         : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
    PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\V
                   S7
    PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS
    PSChildName  : VS7
    PSProvider   : Microsoft.PowerShell.Core\Registry
    

    If you want to access any of the 14.0, 12.0, 11.0, 15.0 values, the solution from the accepted answer will not work - you will get no output:

    PS> (Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7 -Name 15.0).15.0
    PS>
    

    What does work is quoting the value name, which you should probably be doing anyway for safety:

    PS> (Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7" -Name "15.0")."15.0"
    C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
    PS> 
    

    Thus, the accepted answer should be modified as such:

    PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"
    PS> $value = "15.0"
    PS> (Get-ItemProperty -Path $key -Name $value).$value
    C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
    PS> 
    

    This works in PowerShell 2.0 through 5.0 (although you should probably be using Get-ItemPropertyValue in v5).

提交回复
热议问题