Search code examples
listpowershellregistry

Editing a MultiString Array for a registry value in Powershell


How do I create a new MultiString Array and pass it to the registry remotely using Powershell 2.0?

#get the MultiLine String Array from the registry
$regArry = (Get-Itemproperty "hklm:\System\CurrentControlSet\Control\LSA" -name "Notification Packages").("Notification Packages")

#Create a new String Array
[String[]]$tempArry = @()

#Create an ArrayList from the Registry Array so I can edit it
$tempArryList = New-Object System.Collections.Arraylist(,$regArry)


# remove an entry from the list
if ( $tempArryList -contains "EnPasFlt" )
{   
    $tempArryList.Remove("EnPasFlt")
}


# Add an entry
if ( !($tempArryList -contains "EnPasFltV2x64"))
{
    $tempArryList.Add("EnPasFltV2x64")
}

# Convert the list back to a multi-line Array  It is NOT creating new Lines!!!
foreach($i in $tempArryList) {$tempArry += $1 = "\r\n"]}


# Remove the old Array from the Registry
(Remove-ItemProperty "hklm:\System\CurrentControlSet\Control\Lsa" -name "notification packages").("Notification Packages")

# Add the new one
New-itemproperty "hklm:\System\CurrentControlSet\Control\Lsa" -name "notification packages" -PropertyType MultiString -Value "$tempArry"

Everything works great except that i can't get the values to go to a new line. I've tried /r/n and 'r'n. My output in the registry show everything on one line and adds the literal newline and carriage return flags that I add. How do i get the Array to recognize these and not literally print them?


Solution

  • There's no need for fiddling around with ArrayList and linebreaks. Particularly if you want to modify a remote registry. Simply use the Microsoft.Win32.RegistryKey class:

    $server = '...'
    
    $subkey = 'SYSTEM\CurrentControlSet\Control\LSA'
    $value  = 'Notification Packages'
    
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $server)
    $key = $reg.OpenSubKey($subkey, $true)
    $arr = $key.GetValue($value)
    
    $arr = @($arr | ? { $_ -ne 'EnPasFlt' })
    if ($arr -notcontains 'EnPasFltV2x64') {
      $arr += 'EnPasFltV2x64'
    }
    
    $key.SetValue($value, [string[]]$arr, 'MultiString')