如何使用PowerShell迭代远程注册表项?

时间:2018-03-07 14:27:16

标签: .net powershell powershell-v2.0 powershell-v3.0

我有一个powershell脚本,它通过注册表项中的名称值对列表并执行一些操作。所有这些都发生在下面的foreach-object循环

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
            }
} 

这在我的本地机器上运行得非常好。我必须在远程机器注册表上做同样的事情。如何如上所示迭代?

我试过了:

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

但这只会返回我的注册表folde的名称,我无法迭代它

2 个答案:

答案 0 :(得分:1)

Invoke-Command应该做你想做的事。像这样:

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
        }
} 
}

由于你在本地定义了$ masterlist,你可以使用$ Using:masterlist - 见Remote Variables

您还应该考虑使用PSSessions

答案 1 :(得分:0)

这种做法怎么样?

应该递归地获取远程计算机上的所有子项&& 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