Better way to query remote server registries?

1.8k Views Asked by At

I've built this small block of code to query and store the values of a group of servers, which seems to work fine, however I'd like to know if there is a "pure PowerShell" way to do this.

$eServers = Get-ExchangeServer
$Servers = $eServers | ?{$_.Name -like "Delimit_server_group"}
foreach ($server in $Servers)
    {
    [string]$Key1 = "\\$server\HKLM\SYSTEM\CurrentControlSet\Control\"
    [string]$rKeys += (REG QUERY "$key1" /s)
    }
2

There are 2 best solutions below

0
Mathias R. Jessen On

You can use the RegistryKey class to open a remote registry:

$RemoteHKLM = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$server)
$RemoteKey = $RemoteHKLM.OpenSubKey('SYSTEM\CurrentControlSet\Control')
# Following will return all subkey names
$RemoteKey.GetSubKeyNames()

You'll have to implement recursive traversal yourself if you need functionality equivalent to reg query /s

0
Ansgar Wiechers On

Matthias' answer is probably your best option, but there are other approaches you could take as well. If you have PSRemoting enabled on your systems, you could for instance invoke remote commands like this:

$key = 'HKLM:\SYSTEM\CurrentControlSet\Control'

Invoke-Command -Computer $Servers -ScriptBlock {
    Get-ChildItem $args[0] | Select-Object -Expand Name
} -ArgumentList $key