0

I am running a PowerShell command like this in a VBScript.

Below is the VBScript I am running

'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)

So when Enable-Mailbox command fails it does not come back with the error message. How should I capture that message and send it back to the user?

1
  • try / catch Enable-Mailbox. Return a non-zero exit code when it doesn't work out. Document the meaning of the error codes or just log it. Inspect %LASTEXITCODE%. Or just move everything into PowerShell and get rid of the wrapper :) Commented Aug 19, 2016 at 13:58

1 Answer 1

1

Enable-Mailbox doesn't seem to return anything, but it should at least set the automatic variable $?, which indicates whether the last cmdlet was run successfully or not.

You could cast the boolean value of that variable to an integer and return that as the exit code:

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

What you currently have in your PowerShell command string (...; "exit 0") doesn't do anything anyway, since it merely echoes the string "exit 0" without actually setting an exit code (so the default 0 is returned). But even if you removed the double quotes around that statement it would still always return 0.

By setting a proper exit code you can take the numeric value and convert it back to a boolean (0False, 1True):

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

or just take the numeric value:

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

However, for the latter you should invert the return value (exit [int](!$?)), since by convention a numeric exit status 0 indicates success, whereas numeric non-zero exit codes are used for signaling error states.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.