首页 > 解决方案 > PowerShell 直到步入循环

问题描述

我正在尝试编写一个脚本,该脚本将使用 PSWindowsUpdate 更新 Windows。我希望脚本持续运行 PSWindowsUpdate,直到没有更多更新需要安装。该脚本在最后一个“直到”命令上失败,指示:

直到:术语“直到”不被识别为 cmdlet、函数的名称,
脚本文件或可运行的程序。检查名称的拼写,或者如果路径
已包含,请验证路径是否正确,然后重试。
在 C:\Users\user\Desktop\Install-WindowsUpdates-Edit.ps1:63 char:2
+ } 直到 ($updates -eq $null)
+ ~~~~~
    + CategoryInfo : ObjectNotFound: (直到:String) [], CommandNotFoundException
    +fullyQualifiedErrorId:CommandNotFoundException

直到上面几行没有问题。我能看到的所有括号都是用{}each 完成的。我不明白为什么会发生这个错误。

<#
.SYNOPSIS
This script will automatically install all avaialable windows updates on a device and will automatically reboot if needed, after reboot, windows updates will continue to run until no more updates are available. Pilfered     from: https://www.altaro.com/msp-dojo/powershell-windows-updates/#comment-272
#>

"Installing NuGet Package Provider"

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

"Installing the PSWindowsUpdate module"

Install-Module PSWindowsUpdate -Force

# retrieves a list of available updates
"Checking for new updates"

$updates = Invoke-Command -ScriptBlock {Get-WUList -Verbose}

# counts how many updates are available
$updatenumber = ($updates.kb).Count

# if there are available updates proceed with installing the updates and then reboot
if ($updates -ne $null) {
    # Command to install windows updates, creates a scheduled task on the computer
    $Script = {
        Import-Module PSWindowsUpdate;
        Get-WindowsUpdate -AcceptAll -Install | Out-File C:\PSWindowsUpdate.log
    }

    Invoke-WUJob -Script $Script -Confirm:$false -RunNow

    # Show update status until the amount of installed updates equals the same as the amount of updates available

    sleep -Seconds 30

    do {
        $updatestatus = Get-Content c$\PSWindowsUpdate.log

        "Currently processing the following update:"
        Get-Content c$\PSWindowsUpdate.log | select-object -last 1

        sleep -Seconds 10

        $ErrorActionPreference = 'SilentlyContinue'
        $installednumber = ([regex]::Matches($updatestatus, "Installed" )).Count
        $ErrorActionPreference = 'Continue'
    } until ($installednumber -eq $updatenumber)

    # restarts the remote computer and waits till it starts up again

    "restarting computer"

    Restart-Computer -Wait -Force
} until ($updates -eq $null) #ERROR THROWN HERE

# removes schedule task from computer
#Invoke-Command -ScriptBlock {Unregister-ScheduledTask -TaskName PSWindowsUpdate -Confirm:$false}

Remove-Module -Name "PSWindowsUpdate"

"Windows is now up to date"

标签: powershell

解决方案


推荐阅读