0

我正在尝试读取远程注册表中的字符串。当我运行我正在处理的脚本时,它会连接到列表中的工作站,但它在运行时只读取本地计算机,而不是远程计算机。有任何想法吗?

#create open dialog box
Function Get-FileName($initialDirectory)
{
    [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' );
    $d = New-Object Windows.Forms.OpenFileDialog;
    $d.ShowHelp = $True;
    $d.filter = "Comma Separated Value (*.csv)| *.csv";
    $d.ShowDialog( ) | Out-Null;
    $d.filename;
}

# Set Variables with arguments
$strFile = Get-FileName;
$strComputer = Get-Content $strFile;
$date = Get-Date -Format "MM-dd-yyyy";
$outputFile = "C:\PowerShell\Reports";

$cred = Get-Credential

foreach($computer in $strComputer)
{
Enter-PSSession $computer -Credential $cred
Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Reliability
$systemInfo = Get-Item -Name LastComputerName
Write-Host $systemInfo
}
4

2 回答 2

3
foreach($computer in $strComputer)
{
Enter-PSSession $computer -Credential $cred
..
..
}

上面的代码不起作用。Enter-PSSession不适合在脚本中使用。此后在脚本中编写的任何内容都不会运行。

相反,使用Invoke-Command并将脚本块的其余部分作为参数值传递。例如,

foreach ($computer in $strComputer) {
   Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock {
      Set-Location HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Reliability
      $systemInfo = Get-Item -Name LastComputerName
      Write-Host $systemInfo
   }
}
于 2013-06-15T05:42:22.973 回答
2

正如评论已经解释的那样,Enter-PSSession用于交互式使用。要读取远程注册表项,有几种方法。

使用 plain reg.exe,它工作得很好。像这样,

foreach($computer in $strComputers) {
  reg query \\$computer\hklm\software\Microsoft\Windows\CurrentVersion\Reliability  /v LastComputerName
}

使用 PSSession。创建会话并Invoke-Command读取注册表。像这样,

function GetRegistryValues {
  param($rpath, $ivalue)
  Set-Location $rpath
  $systemInfo = (Get-ItemProperty .).$ivalue
  Write-Host $systemInfo
}
$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -Scriptblock ${function:GetRegistryValues} `
 -argumentlist "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Reliability",`
 "LastComputerName"
Remove-PSSession $session

使用 .Net 类,Microsoft.Win32.RegistryKey。像这样,

$sk = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $server)
$k = $sk.opensubkey("SOFTWARE\Microsoft\Windows\CurrentVersion\Reliability", $false)
write-host $k.getvalue("LastComputerName")
于 2013-06-15T05:45:54.630 回答