Skip to content

Instantly share code, notes, and snippets.

@yyano
Last active May 11, 2021 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyano/0940e35ec7c5e3dadd57c5744cfff71b to your computer and use it in GitHub Desktop.
Save yyano/0940e35ec7c5e3dadd57c5744cfff71b to your computer and use it in GitHub Desktop.
Windows Update
## Windows 10 バージョン1607およびWindows Server 2016のみ実行可能
## from https://qiita.com/asterisk9101/items/8a52562ade6d2a47a467
# 1. ログの記録を開始する
$log = ".\$($env:ComputerName)_$(date -f yyyyMMdd).txt"
Start-Transcript $log
$Env:ComputerName
$Env:UserName
date
# 2. Windows Update を確認するセッションを開始
$updateSession = New-Object -com Microsoft.Update.Session
# 3. Windows Update の検索
$searcher = $updateSession.CreateUpdateSearcher()
$searchResult = $searcher.search("IsInstalled=0 and Type='software'")
# 4. Windows Update の結果確認
$searchResult.Updates | % { $_.title -replace ".*(KB\d+).*", "`$1`t$&" }
# 5. 手作業が不要な項目だけを抽出する(通常は検索結果すべて)
$updatesToDownload = New-Object -com Microsoft.Update.UpdateColl
$searchResult.Updates | ? { -not $_.InstallationBehavior.CanRequestUserInput } | ? { $_.EulaAccepted } | % { [void]$updatesToDownload.add($_) }
# 6. ダウンロードする
$downloader = $updateSession.CreateUpdateDownloader()
$downloader.Updates = $updatesToDownload
$downloader.Download()
# 7. ダウンロードが完了したものだけ抽出(通常は全てダウンロードされる)
$updatesToInstall = New-Object -com Microsoft.Update.UpdateColl
$searchResult.Updates | ? { $_.IsDownloaded } | % { [void]$updatesToInstall.add($_) }
# 8. インストールする
$installer = $updateSession.CreateUpdateInstaller()
$installer.Updates = $updatesToInstall
$installationResult = $installer.Install()
# 9. インストールの結果を確認する(ResultCode 2 なら成功、3以上なら一部または全て失敗)
$installationResult
# 10. 再起動する(自動でStop-Transcriptされる)
date
restart-computer
# 面倒な“Windows 10の更新”をスクリプト化できる新たな選択肢(その2):企業ユーザーに贈るWindows 10への乗り換え案内(30) - @IT
# https://www.atmarkit.co.jp/ait/articles/1808/22/news011.html
$updates = Start-WUScan
if ($updates.Count -gt 0) {Install-WUUpdates -Updates $updates} else {Write-Host "No update"}
if (Get-WUIsPendingReboot) {Restart-Computer}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment