Powershell,用于在安装Windows更新后检查重新启动状态



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

$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 对象属性和方法不会显示任何内容。您可以在之前查询更新以查看它们是否可能触发重新启动,但这并不能保证客户端的反应。

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

如果 WindowsUpdate 安装了需要重新启动的修补程序,则应在此位置保留注册表项:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionWindowsUpdateAuto UpdateRebootRequired

因此,您只需要检查该键中是否有任何值即可知道其就 WU 而言的挂起状态。

$pendingRebootKey = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionWindowsUpdateAuto UpdateRebootRequired"
$results = (Get-Item $pendingRebootKey -ErrorAction SilentlyContinue).Property
if($results){
# Reboot is pending
}

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

请注意, 重新启动所需的密钥会在计算机重新启动时自动删除 易失性(仅保存在内存中(。

这可能会隐藏其他潜在问题,因此您可能需要将逻辑更改为 try/catch,并查看特定错误,例如ItemNotFoundException如果有问题。

最新更新