How to iterate through remote registry keys using

2019-09-20 02:33发布

问题:

I have a powershell script that goes through a list of name value pairs in a registry key and do some maniuplations. All of this happens inside the below foreach-object loop

Get-ChildItem "HKLM:\SOFTWARE\PathA\pathB" -Recurse | ForEach-Object {
       $regkey = (Get-ItemProperty $_.PSPath) | Where-Object { $_.PSPath -match 'debug' }
       if ($masterList.Contains($_.Name)) #Check if the reg key is in master list
            {
                   Set-ItemProperty -Path $regkey.PSPath -Name $_.Name -Value 1
            }
} 

This works perfectly fine in my local machine. I have to do the same but on remote machines registry. How can i iterate through as seen above?

I have tried:

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $server)
$key="HKLM:\SOFTWARE\PathA\pathB"
foreach ($subkey in $reg.OpenSubKey($key).GetSubKeyNames())
{
}

But this will just return me the name of the registry folderand i am not able to iterate through it

回答1:

Invoke-Command should do what you want. Something like this:

Invoke-Command -ComputerName DC1 -ScriptBlock {
Get-ChildItem "HKLM:\SOFTWARE\PathA\pathB" -Recurse | ForEach-Object {
   $regkey = (Get-ItemProperty $_.PSPath) | Where-Object { $_.PSPath -match 'debug' }
   if ($Using:masterList.Contains($_.Name)) #Check if the reg key is in master list
        {
               Set-ItemProperty -Path $regkey.PSPath -Name $_.Name -Value 1
        }
} 
}

Since you have $masterlist defined locally, you can use $Using:masterlist - see Remote Variables

You should also considering using PSSessions



回答2:

What about this approach?

Should recursively get you all the subkeys at the remote computer && root_key:

Function remote_registry_query($target, $key)
{
   Try {
        $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $target)
        ForEach ($sub in $registry.OpenSubKey($key).GetSubKeyNames())
        {
            $subkey = $registry.OpenSubKey("$($key)\$($sub)")
            ForEach ($value in $subkey.GetValueNames())
            {
                Write-Output $subkey.GetValue($value)
            }
            remote_registry_query -target $computer -key "$($key)\$($sub)"
        }
  } Catch [System.Security.SecurityException] {
        "Registry - access denied $($key)"
  } Catch {
        $_.Exception.Message
  }
}

$computer = "remote computer name"
$root_key = 'HKLM:\SOFTWARE\PathA\pathB'
remote_registry_query -target $computer -key $root_key