Windows 还有一些鲜为人知的com对象,支持操作windows 更新,下面的例子会列出机器的 windows 更新历史。
$Session = New-Object -ComObject Microsoft.Update.Session $Searcher = $Session.CreateUpdateSearcher() $HistoryCount = $Searcher.GetTotalHistoryCount() $Searcher.QueryHistory(1,$HistoryCount) | Select-Object Date, Title, Description
仅仅展示已安装的更新,作用不大,能够自动检查并安装更新或者打补丁就更完美了。下面的脚本可以完成自动更新:
$objSession = New-Object -ComObject "Microsoft.Update.Session" $objSearcher= $objSession.CreateUpdateSearcher() $searchResult = $objSearcher.Search("IsInstalled=0 and Type='Software'") if($searchResult.Updates.Count -lt 1) { exit } $updatesToDownload=New-Object -ComObject "Microsoft.Update.UpdateColl" foreach($update in $searchResult.Updates) { $updatesToDownload.Add($update) write-Host "Download available: $($update.Title)" } $downloader = $objSession.CreateUpdateDownloader() $downloader.Updates = $updatesToDownload $downloader.Download() $updatesToInstall = New-Object -ComObject "Microsoft.Update.UpdateColl" foreach($update in $searchResult.Updates) { if($update.IsDownloaded) { $updatesToInstall.Add($update) write-Host "Ready to install: $($update.Title)" } } $installer = $objSession.CreateUpdateInstaller() $installer.Updates = $updatesToInstall $batchResult = $installer.Install() foreach($individualResult in $batchResult) { write-Host "Install finished: $(individualResult.Title) | $(individualResult.ResultString)" }
已经有牛人帮我们写好了一个module:Windows Update PowerShell Module,里面包括9个函数:
- Add-WUOfflineSync
- Get-WUHistory
- Get-WUInstall
- Get-WUInstallerStatus
- Get-WUList
- Get-WURebootStatus
- Get-WUServiceManager
- Get-WUUninstall
- Remove-WUOfflineSync
下载后会发现,里面调用的全部是com对象的方法。
原文链接:http://powershell.com/cs/blogs/tips/archive/2012/09/27/listing-windows-updates-with-powershell.aspx
本文链接: https://www.pstips.net/powershell-listing-windows-updates.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
Install-Module PSWindowsUpdate 拿到的版本好像更新一点
foreach($individualResult in $batchResult)
{
write-Host “Install finished: $(individualResult.Title) | $(individualResult.ResultString)”
}
$(individualResult.Title) 、$(individualResult.ResultString) 这个貌似有些问题吧?