locked
Read ExpandString from Registry without Expansion RRS feed

  • Question

  • I have an ExpandString value in the Registry. I want to read its data verbatim, without expanding any of the variables within.  How do I do that? CAN I do that?

    Specifically, someone (probably me), or something (probably one of my scripts) has changed the value type of Path in HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path from ExpandString to String.  I'm trying to create a script that will read the data, delete or rename the Path value, and then create a new value with the correct type and data.

    Wednesday, September 20, 2017 6:00 PM

Answers

  • $item = get-item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    $item.GetValueKind('Path') $item.GetValue('Path','','DoNotExpandEnvironmentNames') -split ';' #
    # Set value to specific kind # $item.SetValue('Path',$newpath,[Microsoft.Win32.RegistryValueKind]::ExpandString)



    \_(ツ)_/




    • Edited by jrv Wednesday, September 20, 2017 6:29 PM
    • Marked as answer by JT65 Thursday, September 21, 2017 12:19 PM
    Wednesday, September 20, 2017 6:26 PM

All replies

  • $item = get-item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    $item.GetValueKind('Path') $item.GetValue('Path','','DoNotExpandEnvironmentNames') -split ';' #
    # Set value to specific kind # $item.SetValue('Path',$newpath,[Microsoft.Win32.RegistryValueKind]::ExpandString)



    \_(ツ)_/




    • Edited by jrv Wednesday, September 20, 2017 6:29 PM
    • Marked as answer by JT65 Thursday, September 21, 2017 12:19 PM
    Wednesday, September 20, 2017 6:26 PM
  • The GetValue method was the missing piece. That and I was using Rename-ItemProperty to make a backup and it was expanding the environment variables in the path.

    Here's the finished product.  I wish I could make those first three lines more elegant, but when I tried to substitute HKEY_LOCAL_MACHINE for HKLM on line 6, I had problems:

    $PathPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
    $PathPath2 = "HKEY_LOCAL_MACHINE\$PathPath"
    $PathPath = "HKLM:\$PathPath"
    If (Test-Path $PathPath)
        {
            If ((Get-Item -Path Registry::$PathPath2).GetValueKind("Path") -ne "ExpandString")
                {
                    $item = get-item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
                    $PathData = $item.GetValue('Path','',1)
                    
                    New-ItemProperty -Path $PathPath -Name 'PathBackup' -PropertyType "ExpandString" -Value $PathData
                    Remove-ItemProperty -Path $PathPath -Name 'Path' -ErrorAction Stop
                    New-ItemProperty -Path $PathPath -Name "Path" -PropertyType "ExpandString" -Value $PathData
                    
                }
                
        }

    Thursday, September 21, 2017 12:25 PM