0

我正在VBScript中运行这样的PowerShell命令。如何从VBScript中的PowerShell获取错误消息

下面是我运行

'This Script is used for creating Mailboxes for Active Directory Users. 
'This script triggers a Power Shell Script which creates the mailbox for the 
'ActiveDirectory User. 
' 
Set args = WScript.Arguments 
'Argument 0 contains the identity User Name 
WScript.Echo args.Item(0) 
'Argument 1 contains the Mail Store Alias Name 
WScript.Echo args.Item(1) 
'Argument 2 contains the Mail Database 
WScript.Echo args.Item(2) 
'Argument 3 contains the Report Log Path 
WScript.Echo args.Item(3) 

On Error Resume Next 

Dim shell 
Set shell = CreateObject("WScript.Shell") 

'Firing the PowerShell command from VBScript 
shell.Run "PowerShell.exe -PSConsoleFile ""E:\Program Files\Microsoft\Exchange Server\Bin\exshell.psc1"" -NoExit ""&{""Enable-Mailbox -Identity '"&Replace(args.Item(0),"'", "''")&"' -Alias '"&args.Item(1)&"' -Database '"&args.Item(2)&"';""exit 0""} ",,20 

If Err.Number <> 0 Then 
    WScript.Echo("Error Occurred in CreateMailBoxExchange script" & Err.Description) 
    WScript.Quit(2) 
End If 
WScript.Quit(3) 

所以当Enable-Mailbox命令失败,它不回来与错误消息的VBScript。我应该如何捕获该消息并将其发回给用户?

+0

try/catch启用邮箱。当它不工作时返回一个非零的退出代码。记录错误代码的含义或只记录它们。检查%LASTEXITCODE%。或者只是将所有东西都移到PowerShell中,然后摆脱包装:) –

回答

1

Enable-Mailbox似乎没有返回任何内容,但它至少应设置automatic variable$?,它表示最后一个cmdlet是否已成功运行。

你可以变量的布尔值转换为整数,并返回退出代码:

Enable-Mailbox ...; exit [int]$? 

你目前在你的PowerShell命令字符串(...; "exit 0")什么都不做什么呢,因为它只是在不实际设置退出代码的情况下回显字符串"exit 0"(因此返回默认值0)。但是,即使你删除周围的语句双引号也仍然始终返回0

通过设置适当的退出代码,你可以采取的数值,并将其转换回一个布尔(0False1True) :

enabled = CBool(shell.Run("...", 0, True)) 

或只取数值:

exitcode = shell.Run("...", 0, True) 

然而,对于后者,你应该反转日e返回值(exit [int](!$?)),因为按照惯例,数字退出状态0指示成功,而数字非零退出代码用于指示错误状态。

相关问题