安装 windows 更新后用于检查重启状态的 Powershell

Powershell for checking reboot status after installing windows updates

这是我用于搜索 WSUS 安装的 Windows 更新的代码,我想为重启状态添加一列 pending/done。有开关吗?

$Session = New-Object -ComObject "Microsoft.Update.Session"

$Searcher = $Session.CreateUpdateSearcher()

$historyCount = $Searcher.GetTotalHistoryCount()

$Searcher.QueryHistory(0, $historyCount) | Select-Object Date,

   @{name="Operation"; expression={switch($_.operation){

       1 {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}}}},

   @{name="Status"; expression={switch($_.resultcode){

       1 {"In Progress"}; 2 {"Succeeded"}; 3 {"Succeeded With Errors"};

       4 {"Failed"}; 5 {"Aborted"}

}}}, Title | Out-GridView

简要查看 COM 对象属性和方法并没有显示任何内容。 You can query update before to see if they might trigger a reboot 但这并不能保证客户会如何反应。

可能还有其他方法,但如果您想确定当前状态,一个建议是查看注册表。

If a patch was installed by WindowsUpdates that requires a reboot it should leave a registry entry in this location:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired

因此,您只需要检查该键中是否有 any 值,就 WU 而言,了解其待处理状态。

$pendingRebootKey = "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"
$results = (Get-Item $pendingRebootKey -ErrorAction SilentlyContinue).Property

if($results){
    # Reboot is pending
}

使用 -ErrorAction 很有用,因为根据文章:

Note that the RebootRequired key is automatically deleted when the machine reboots as it's volatile (only held in memory).

这可能会隐藏其他潜在问题,因此您可能需要将逻辑更改为 try/catch 并查看 ItemNotFoundException 之类的具体错误(如果有顾虑的话)。