![](/img/trans.png)
[英]How to run windows update after creation of azure virtual machine via powershell?
[英]Windows Update via Powershell IndexOutOfRangeException
我正在尝试通过 PowerShell 安装 windows 更新,利用来自WUApi的 COM 对象。
这是我到目前为止得到的代码。
$updateSession = New-Object -com Microsoft.update.Session
$updateSearcher = $UpdateSession.CreateUpdateSearcher()
$updateResult = $updateSearcher.Search("IsInstalled=0 and Type='Software'");
$needsRestart = $false
foreach($update in $updateResult.Updates) {
$needsRestart = $needsRestart -or $update.InstallationBehavior.RebootBehavior -ne 0
}
$updateDownloader = $UpdateSession.CreateUpdateDownloader()
$updateDownloader.Updates = $updateResult.Updates
$downloadResult = $updateDownloader.Download()
当我运行这段代码时,我得到了IndexOutOfRangeException
。
Index was outside the bounds of the array.
At C:\Users\MyUser\Documents\Update-Windows2.ps1:9 char:1
+ $updateDownloader.Updates = $updateResult.Updates
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
我已经检查并仔细检查过,但似乎找不到问题出在哪里。 我用 C# 代码尝试了类似的逻辑,它似乎可以毫无问题地分配Updates
变量。
知道我在这里缺少什么吗? 提前致谢。
无法重现,但我很确定“$updateResult.Updates”是 $null(= 没有可用的更新)你能检查一下吗?
如果是这样,添加一个 if 条件(与集合一起使用时在左侧为 null!)
if ($null -ne $updateResult.Updates) {
$updateDownloader.Updates = $updateResult.Updates
$downloadResult = $updateDownloader.Download()
}
为什么 $null 在左边? (不分PS版本): https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1#checking-for-null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.