Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
lit Avatar asked Oct 29 '22 07:10

lit


1 Answers

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

Indeed, PowerShell's Get-ItemProperty / Get-ItemPropertyValue cmdlets currently (Windows PowerShell v5.1 / PowerShell Core 6.1.0-preview.4) 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.

like image 170
mklement0 Avatar answered Nov 15 '22 06:11

mklement0