首页 > 解决方案 > 在 PowerShell 中检查“invoke-vmscript”cmdlet 的状态

问题描述

我正在使用本地 WSUS 服务器创建一个 PowerShell 脚本来更新我的环境中的服务器 (esxi vms)。我决定使用 vm 工具与 vm 交互,而不是使用 WinRM。我选择这种方法是因为所有 vm 都安装了 vmtools。

由于我采用这种方法,因此我使用“invoke-vmscript”命令将 PowerShell 函数发送到 vm 并运行代码。该代码包括确保服务正在运行、查看更新、安装和之后重新启动。由于我使用这种方法,我无法知道脚本是否被冻结。有没有办法启动“invoke-vmscript”并定期轮询状态(以某种方式)以确定需要多长时间?

或者,有没有办法查看 Windows 更新的当前状态。任何一种方法对我来说都很好。

下面是一段代码。

# Find all updates that will be installed on vm
Function PreStage{

Write-Host "Beginning prestage..."
$service = Get-Service -Name "wuauserv" # Check if Update 
service is running
if ($service.Status -eq "Stopped") # If not running...
    {
    Write-Host "wuau service is stopped... Starting"
    Invoke-Command -ScriptBlock {Start-Service wuauserv} # 
Start service
        [System.Threading.Thread]::Sleep(3000)
    Invoke-Command -ScriptBlock {wuauclt.exe /detectnow} # Checking with WSUS server
        [System.Threading.Thread]::Sleep(1500)
    Write-Host "Checking Complete"
    }
Install-PackageProvider Nuget -Force | Out-Null # Install update dependencies
Install-Module PSWindowsUpdate -Confirm:$False -Force | Out-Null
Write-Host "Checking for Windows Update"
$updates = Get-WindowsUpdate -Category 'Security Updates', 'Critical Updates' # List available updates 
if ($updates -eq $null)# If there are no updates available...
    {
    Write-Host "There are no available updates at this time"
    exit 5
    }
else
    {
    Write-Host "The following updates will be installed from the WSUS server" # Display updates that will be installed
    Write-Host ""
    $updates | select KB, Size, Title | ft 
    }
}  # Function to pre-stage update
$CheckForUpdates = Invoke-VMScript -VM $vm -ScriptType 
Powershell -ScriptText ${function:PreStage} -GuestCredential 
$Credentials 
$CheckForUpdates.ScriptOutput 
while ($CheckForUpdates.ExitCode -ne 5)
    {
    $Update = Invoke-VMScript -VM $vm -ScriptType Powershell ScriptText {Get-WindowsUpdate -AcceptAll -Install -Category 'Security Updates', 'Critical Updates' -RecurseCycle 2} -GuestCredential $Credentials
    sleep 60
    Write-Host "Restarting $vm after updates..."
    Restart-vm -vm $vm -Confirm:$false | Out-Null
    Sleep 60
    Write-Host "Waiting for $vm to be back online..."
    Wait-Tools -VM $vm | Out-Null
    $CheckForUpdates = Invoke-VMScript -VM $vm -ScriptType Powershell -ScriptText ${function:PreStage} -GuestCredential $Credentials 
$CheckForUpdates.ScriptOutput 
}

标签: powershelldevopspowercliwinrmesxi

解决方案


推荐阅读