You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell获取服务器更新详情及最后重启时间

合并Windows更新与服务器重启时间至同一表格的PowerShell解决方案

目标生成如下格式的每日日志:

Source        Description      HotFixID      InstalledOn             LastRebooted          
------        -----------      --------      -----------             -----------               
SRV1...       Update           KB4049065     2/2/2018 12:00:00 AM    1/2/2019 10:00:00 AM 
SRV2...       Security Update  KB4048953     2/2/2018 12:00:00 AM    2/2/2019 09:00:00 AM  

问题背景

已实现两段独立PowerShell代码:

  1. 按日期排序显示系统更新:
get-wmiobject -class win32_quickfixengineering | Sort-Object -Property {$_.InstalledOn} -Descending
  1. 查询服务器最后重启时间:
Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime

尝试合并时使用以下代码,但LastBootUpTime列始终为空:

get-wmiobject -class win32_quickfixengineering | Sort-Object -Property {$_.InstalledOn} -Descending | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

得到结果:

csname   LastBootUpTime
------   --------------
SRV1... 
SRV2...

错误原因

Win32_QuickFixEngineering类的对象不包含lastbootuptime属性,所以在计算属性里调用$_.lastbootuptime时无法获取有效值,导致列为空。同时,ConvertToDateTime是CIM实例的专属方法,WMI对象的时间转换逻辑与此不同。

正确实现方法

单服务器场景

先单独获取服务器的最后重启时间并保存到变量,再处理更新列表时将该值作为固定列添加(避免重复查询系统信息,提升效率):

# 获取当前服务器的最后重启时间
$lastReboot = (Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime

# 获取更新列表并合并重启时间列,匹配目标日志格式
Get-WmiObject -Class Win32_QuickFixEngineering | 
    Sort-Object -Property InstalledOn -Descending | 
    Select-Object -Property @{Label='Source';Expression={$_.CSName}},
                            Description,
                            HotFixID,
                            @{Label='InstalledOn';Expression={$_.ConvertToDateTime($_.InstalledOn)}},
                            @{Label='LastRebooted';Expression={$lastReboot}}

多服务器场景

如果需要批量处理多台服务器,可通过循环遍历实现:

# 定义目标服务器列表
$servers = @("SRV1", "SRV2")

foreach ($server in $servers) {
    # 获取当前服务器的最后重启时间
    $lastReboot = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName $server).LastBootUpTime
    
    # 获取该服务器的更新列表并合并重启时间
    Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName $server | 
        Sort-Object -Property InstalledOn -Descending | 
        Select-Object -Property @{Label='Source';Expression={$_.CSName}},
                                Description,
                                HotFixID,
                                @{Label='InstalledOn';Expression={$_.ConvertToDateTime($_.InstalledOn)}},
                                @{Label='LastRebooted';Expression={$lastReboot}}
}

关键说明

  • WMI对象的InstalledOn是特殊日期格式,需通过$_.ConvertToDateTime()转换为可读时间格式
  • 提前获取并复用LastBootUpTime,避免每条更新都重复查询系统信息
  • 通过计算属性@{Label='列名';Expression={值}}自定义表格列名,完全匹配目标日志格式

内容的提问来源于stack exchange,提问作者StackBuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:17:16