Skip to content

用 PowerShell 给 Windows 系统安装补丁并自动重启 #146

@Dream4ever

Description

@Dream4ever

需求描述

之前实现了 PowerShell 调用阿里云 Cli 创建手动快照并重启实例,现在由于需要时不时地给阿里云服务器上的 Windows 打补丁,之前都是等手动快照创建完成之后再人工打补丁,太麻烦了,所以研究了一下自动化实现该需求的解决方案。

整体流程

需要先在 PowerShell 中安装 PSWindowsUpdate 这个模块,有了它就可以检查当前的 Windows 系统是否有需要安装的补丁,并且还可以用它来安装补丁,并在安装完成后自动重启 Windows 系统。

然后编写下面的 PowerShell 脚本,用来检查当前 Windows 系统是否有需要安装的补丁,如果有则自动安装,并在安装完成后自动重启。

$output = Get-WindowsUpdate | Out-String
$updates = ([regex]'KB(\d)+').Matches($output)
if ($updates.Count -gt 0) {
  Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
}

然后把上面的脚本添加到 Windows 的计划任务中,定时执行:

image

image

image

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    ServerThe invisible hero

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions