Search code examples
powershellregistry

How to retrieve original, unresolved (unexpanded) registry value?


In the System Properties > Environment Variables > User variables > PATH contains:

%USERPROFILE%\Downloads\SysinternalsSuite;%USERPROFILE%\bin

The value can be retrieved with:

PS C:\src\t> (Get-ItemProperty -Path HKCU:\Environment).PATH
C:\Users\lit\Downloads\SysinternalsSuite;C:\Users\lit\bin

Is there any way to get the original value without variable expansion? It almost seems like Get-ItemProperty needs a -Raw switch.


Solution

  • PetSerAl, as many times before, has provided an effective solution in a terse comment on the question.

    Indeed, PowerShell's Get-ItemProperty / Get-ItemPropertyValue cmdlets currently (PowerShell 7.3.0) lack the ability to retrieve a REG_EXPAND_SZ registry value's raw value, meaning the value as stored in the registry before the embedded environment-variable references (e.g., %USERPROFILE%) are expanded (interpolated).

    Direct use of the .NET API is therefore needed:

    (Get-Item -Path HKCU:\Environment).GetValue(
      'PATH',  # the registry-value name
      $null,   # the default value to return if no such value exists.
      'DoNotExpandEnvironmentNames' # the option that suppresses expansion
    )
    

    See [Microsoft.Win32.RegistryKey].GetValue().

    Note: 'DoNotExpandEnvironmentNames' is automatically converted to [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentVariables by PowerShell; you may use the latter as well.