【发布时间】:2015-03-17 04:49:30
【问题描述】:
今天我的一个 PowerShell 脚本中出现了一个奇怪的问题:
环境信息:我所说的 PowerShell 脚本正在被 VBScript 调用。
if($VM -eq "Yes") {
Add-PSSnapin VMware.VimAutomation.Core
Connect-VIServer -Server $VMHost -User $VMUser -Password $VMPassword
$Snapshot = $null
Try {
$Snapshot = New-Snapshot -Name $NameofSnapshot -VM $ServerName -Memory
$CurrentPatchingState = "1;$Servername;Status=1;$(Get-Date -format 'dd.MM.yyyy hh:mm:ss') Created Snapshot" | Out-File -Filepath "C:\$Servername.txt" -Append -encoding ASCII
} Catch [system.exception] {
$CurrentPatchingState = "2;$Servername;Status=2;$(Get-Date -format 'dd.MM.yyyy hh:mm:ss') Wasnt able to take a Snapshot - Aborting" | Out-File -Filepath "C:\$Servername.txt" -Append -encoding ASCII
Disconnect-VIServer -Server $VMHost -Confirm:$false
exit
}
if ($Snapshot -eq $null) {
$CurrentPatchingState = "2;$Servername;Status=2;$(Get-Date -format 'dd.MM.yyyy hh:mm:ss') Wasnt able to get a Clean Snapshot - Aborting" | Out-File -Filepath "C:\$Servername.txt" -Append -encoding ASCII
Disconnect-VIServer -Server $VMHost -Confirm:$false
exit
}
}
今天脚本在这部分失败了。日志文件显示:
2;xxxxxxxxxxxxxxx;Status=2;18.01.2015 11:01:51 Wasnt able to take a Snapshot - Aborting
2;xxxxxxxxxxxxxxx;Status=2;18.01.2015 11:01:51 Wasnt able to get a Clean Snapshot - Aborting
这怎么会发生,因为脚本应该在第一次捕获时停止?
【问题讨论】:
-
你应该在 try 块中使用 break,exit 不是 powershell 关键字。请参阅相关帖子:stackoverflow.com/a/23703056/381149
-
也许我没有让自己足够清楚,我想让hole脚本停止这就是我使用Exit的原因:这将“退出”当前运行的上下文。如果您从脚本调用此命令,它将退出脚本。脚本终止,但在第二个出口不是第一个。
-
退出在
[scriptblock]内,这是它自己的上下文exit'早期'离开该脚本块并返回到父上下文,脚本本身......第二个退出在脚本的上下文,因此正确终止。
标签: powershell exception-handling exit