2012-01-04 61 views
2

我从VBScript运行PS脚本,并且想要在PS中出现错误时在VBScript中抛出异常。这是VBScript代码我用来运行PowerShell的:在VBScript中捕获powershell异常

Option Explicit 
Dim oShell, appCmd 
Set oShell = CreateObject("WScript.Shell") 

appCmd  = "powershell set-executionpolicy unrestricted -force; c:\3.ps1" 
oShell.Run appCmd, 4, true 

这是我PS的脚本:

throw "I'm exception" 

我试过一般的VBScript陷阱:

if(Err.number <> 0) then 
Err.raise() 
end if 

,但它不” t似乎工作。我希望只使用PS并完全摆脱VBScript,但它是另一个运行VB的应用程序,它只支持VB。有任何想法吗?

我可以在PS文件中写入异常,然后从VB检查文件是否存在并抛出异常,但我希望有更好的方法。 感谢

回答

3

在PowerShell脚本使用

exit $MyErrorLevel 

哪里$MyErrorLevel是你自己的代码,你会用VBS检测。

在VBS中,WShell对象Run方法将从PowerShell返回退出代码。

例VBS脚本:

Option Explicit 
Dim oShell, appCmd 
Dim intReturnCode 

Set oShell = CreateObject("WScript.Shell") 

appCmd = "powershell.exe -File c:\Test.ps1" 

intReturnCode = oShell.Run(appCmd, 4, true) 

MsgBox intReturnCode 

例PS脚本(C:\ Test.ps1):

try { 
    1/$null 
} catch { 
    exit 1 
} 

exit 0 
+0

尼斯,效果很好。有没有办法来传递异常消息? – 2012-01-04 08:27:24

+0

我找到了更好的方法:appCmd =“powershell set-executionpolicy unrestricted -force; c:\ 3.ps1; exit $ LASTEXITCODE” - 这样我就不需要在PS中设置退出代码 – 2012-01-04 08:32:43

+1

不是我意识到,对不起。唯一想到的是通过一个文本文件传递它并读取一个非零的退出代码事件,但这是我认为你试图避免的一种方法。 – 2012-01-04 08:37:57