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

前端 未结 9 537
醉酒成梦
醉酒成梦 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:34

    If you create an object, you get a more readable output and also gain an object with properties you can access:

    $path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
    $obj  = New-Object -TypeName psobject
    
    Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
    $command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_)
    $value = Invoke-Expression -Command $command
    $obj | Add-Member -MemberType NoteProperty -Name $_ -Value $value}
    
    Write-Output $obj | fl
    

    Sample output: InstallRoot : C:\Windows\Microsoft.NET\Framework\

    And the object: $obj.InstallRoot = C:\Windows\Microsoft.NET\Framework\

    The truth of the matter is this is way more complicated than it needs to be. Here is a much better example, and much simpler:

    $path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
    $objReg = Get-ItemProperty -Path $path | Select -Property *
    

    $objReg is now a custom object where each registry entry is a property name. You can view the formatted list via:

    write-output $objReg
    
    InstallRoot        : C:\Windows\Microsoft.NET\Framework\
    DbgManagedDebugger : "C:\windows\system32\vsjitdebugger.exe"
    

    And you have access to the object itself:

    $objReg.InstallRoot
    C:\Windows\Microsoft.NET\Framework\
    
    0 讨论(0)
  • 2020-12-13 12:35

    Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):

    $path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';
    
    Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
        $command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
        $value = Invoke-Expression -Command $command;
        $_ + ' : ' + $value; };
    

    Like this:

    DbgJITDebugLaunchSetting : 16

    DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d

    InstallRoot : C:\Windows\Microsoft.NET\Framework\

    0 讨论(0)
  • 2020-12-13 12:41
    $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
    (Get-ItemProperty -Path $key -Name ProgramFilesDir).ProgramFilesDir
    

    I've never liked how this was provider was implemented like this : /

    Basically, it makes every registry value a PSCustomObject object with PsPath, PsParentPath, PsChildname, PSDrive and PSProvider properties and then a property for its actual value. So even though you asked for the item by name, to get its value you have to use the name once more.

    0 讨论(0)
提交回复
热议问题