强化 PowerShell 脚本以使用 PowerCLI 自动使用 VM

Hardening PowerShell Script for Automating Usage of VMs using PowerCLI

为了让 运行 一些其他脚本有一个干净的环境,我需要在每次计划任务触发它时恢复 ESX 主机上的虚拟机。

恢复可以通过 运行ning:

Set-VM -VM $VMName -Snapshot "MySnapshot" -Confirm:$false

启动可以通过运行ning实现:

Start-VM -VM $VMName

停止可以通过运行ning:

来实现
Shutdown-VMGuest -VM $VMName -Confirm:$false

我如何以更安全的方式处理此问题,例如在恢复、启动或停止 VM 时能够处理错误,并在其中一个任务成功执行时获得 return?

我正在使用 PowerCLI 6.5.0。

您可以使用多种方法来实现这一点。 这里有 2 个例子:

  1. 使用 -ErrorVariable

    # Revert VM
    Set-VM -VM $VMName -Snapshot "MySnapshot" -Confirm:$false -ErrorVariable revertError
    
    If ($revertError)
    {
        Write-Host "An error occured while reverting snapshot !" -ForegroundColor Red
        Write-Host $revertError
    }
    Else
    {
        Write-Host "Successfully reverted to snapshot." -ForegroundColor Green
    }
    
    # Start VM
    Start-VM -VM $VMName -ErrorVariable startError
    
    If ($startError)
    {
        Write-Host "An error occured while starting VM :" -ForegroundColor Red
        Write-Host $startError
    }
    Else
    {
        Write-Host "Successfully started VM." -ForegroundColor Green
    }
    
    # Stop VM
    Shutdown-VMGuest -VM $VMName -Confirm:$false -ErrorVariable shutdownError
    
    If ($shutdownError)
    {
        Write-Host "An error occured while shutting down guest OS of VM :" -ForegroundColor Red
        Write-Host $shutdownError
    }
    Else
    {
        Write-Host "Successfully stopped VM." -ForegroundColor Green
    }
    
  2. 使用@mark-wragg 提到的Try/Catch

    # Revert VM
    Try
    {
        # Temporarily make all errors terminating
        $errorActionPreference = "Stop"
        Set-VM -VM $VMName -Snapshot "MySnapshot" -Confirm:$false
        Write-Host "Successfully reverted to snapshot." -ForegroundColor Green
    }
    Catch
    {
        Write-Host "An error occured while reverting snapshot !" -ForegroundColor Red
        Write-Host $_.Exception.Message
    }
    Finally
    {
        $errorActionPreference = "Continue"
    }
    
    # Start VM
    Try
    {
        # Temporarily make all errors terminating
        $errorActionPreference = "Stop"
        Start-VM -VM $VMName
        Write-Host "Successfully started VM." -ForegroundColor Green
    }
    Catch
    {
        Write-Host "An error occured while starting VM :" -ForegroundColor Red
        Write-Host $_.Exception.Message
    }
    Finally
    {
        $errorActionPreference = "Continue"
    }
    
    # Stop VM
    Try
    {
        # Temporarily make all errors terminating
        $errorActionPreference = "Stop"
        Shutdown-VMGuest -VM $VMName -Confirm:$false
        Write-Host "Successfully stopped VM." -ForegroundColor Green
    }
    Catch
    {
        Write-Host "An error occured while shutting down guest OS of VM :" -ForegroundColor Red
        Write-Host $_.Exception.Message
    }
    Finally
    {
        $errorActionPreference = "Continue"
    }