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指示成功,而數字非零退出代碼用於指示錯誤狀態。

相關問題