简体   繁体   中英

PowerShell - How do you get the latest windows updates from a list of servers? Array/For Each problem

I think the issue is in the $computer and foreach sections. When I run this nothing returns. What am I missing please?

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

Thanks for your help.

i think this should work. But at the moment i have no possibility to test it.

Some explanations: name var ADComputer instead of COMPUTER

$COMPUTER and $coMpUTeR and $COMputer and $computer are all the same because of powershell's case-insensitivity

create var outside the loop, if you don't change them in it

if ($KeyValue -lt $System) makes no sense it will always be true, because the last successfull installation will always be in the past

Keep it simple, you can easily get the remote's registry value with the Invoke-Command , which allows you to "invoke" a script block on a remote host and returns its output. Also it is simpler to call the registry with the 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 $computer -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)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM