首页 > 解决方案 > PowerShell - 如何从服务器列表中获取最新的 Windows 更新?数组/每个问题

问题描述

我认为问题出在 $computer 和 foreach 部分。当我运行它时,什么都没有返回。请问我错过了什么?

$computer = @('server1', 'server2')

ForEach ($COMPUTER in (Get-ADComputer -Filter ('Name -like "{0}"' -f $computer))) 
{if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
 
{write-host "cannot reach $computer" -f red}

 
 
else {
  $key = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install" 
        $keytype = [Microsoft.Win32.RegistryHive]::LocalMachine 
        $RemoteBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($keytype,$Server) 
        $regKey = $RemoteBase.OpenSubKey($key) 
        $KeyValue = $regkey.GetValue("LastSuccessTime"”) 
     
        $System = (Get-Date -Format "yyyy-MM-dd hh:mm:ss")  
             
        if    ($KeyValue -lt $System) 
        { 
            Write-Host " " 
            Write-Host $computer "Last time updates were installed was: " $KeyValue 
        } 
    }
} 

谢谢你的帮助。

标签: powershell

解决方案


我认为这应该可行。但目前我没有可能测试它。

一些解释:name var ADComputer 而不是 COMPUTER

$COMPUTER 和 $coMpUTeR 和 $COMputer 和 $computer 都是一样的,因为 powershell 不区分大小写

在循环外创建 var,如果你不改变它们

if ($KeyValue -lt $System) 没有意义,它总是正确的,因为最后一次成功的安装总是在过去

保持简单,您可以使用Invoke-Command轻松获取远程的注册表值,它允许您“调用”远程主机上的脚本块并返回其输出。此外,使用Get-ItemPropertyValue cmdlet调用注册表更简单。

# create array computer
$computer = @('server1', 'server2')

# store Registry key
$key = “HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install” 

# iterate through computers
$computer.Foreach({
    # Get Computer from AD
    $ADComputer = Get-ADComputer $_ 

    # Test if server is not reachable and report it
    if(!(Test-Connection -Cn $ADComputer.DNSHostName -BufferSize 16 -Count 1 -ea 0 -quiet)){
        Write-Host ("cannot reach {0} " -f $_) -ForegroundColor Red
    }else{
        # Get remote computers registry entry
        $KeyValue = Invoke-Command { (Get-ItemProperty -Path $args[0] -Name "LastSuccessTime") } -ComputerName $ADComputer.DNSHostName -ArgumentList $key

        Write-Host " " 
        # write LastSuccessTime to host
        Write-Host ("{0}: Last time updates were installed was: {1}" -f $ADComputer.Name, $KeyValue)
    }
})

推荐阅读