强化PowerShell脚本,用于使用PowerCLI自动使用虚拟机
问题描述:
为了让一个干净的环境运行一些其他脚本,每当计划任务触发它时,我需要在ESX主机上还原虚拟机。强化PowerShell脚本,用于使用PowerCLI自动使用虚拟机
复归可以通过运行来实现:可以实现
Start-VM -VM $VMName
雪夜运行:
Set-VM -VM $VMName -Snapshot "MySnapshot" -Confirm:$false
启动可以通过运行来实现
Shutdown-VMGuest -VM $VMName -Confirm:$false
我该如何处理这以一种更安全的方式,例如能够在恢复,启动或停止虚拟机并获得时处理错误如果这些任务之一正在成功执行,则返回?
我正在使用PowerCLI 6.5.0。
答
您可以使用几种方法来实现此目的。 这里有两个例子:
-
使用-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 }
-
使用try/catch语句通过@标记wragg
# 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" }
作为mentionned看看概念'Try..Catch'如果你以前没有。我在这里写了一篇关于它的博客文章:http://wragg.io/powershell-try-catch/ –