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

时间:2017-04-25 06:38:25

标签: powershell powercli

要获得运行其他脚本的干净环境,每次计划任务触发时,我都需要在ESX主机上还原虚拟机。

恢复可以通过运行:

来实现
Set-VM -VM $VMName -Snapshot "MySnapshot" -Confirm:$false

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

Start-VM -VM $VMName

停止可以通过运行:

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

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

我使用的是PowerCLI 6.5.0。

1 个答案:

答案 0 :(得分:1)

您可以使用多种方法来实现此目的。 以下是两个例子:

  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"
    }