2

I'm running PS scripts from VBScript and would like to throw exception in VBScript if there were errors in PS. This is the VBScript code I use to run 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

This is my PS script:

throw "I'm exception"

I've tried general VBScript catch:

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

but it doesn't seem to work. I would love to use only PS and get rid of VBScript altogether, but it's another application that is running VBs and it only supports VBs. Any ideas?

I could write exception in file in PS and then from VBs check if file exist and throw exception, but I hope there's a better way. Thanks

1 Answer 1

3

In the Powershell script use

exit $MyErrorLevel

Where $MyErrorLevel is your own code you will detect with VBS.

In VBS the WShell object Run method will return the exit code from PowerShell.

Example VBS script:

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

Example PS script (C:\Test.ps1):

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

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

5 Comments

Nice, works well. Is there a way to also pass exception message?
I have found better way: appCmd = "powershell set-executionpolicy unrestricted -force; c:\3.ps1; exit $LASTEXITCODE" - this way I will not need to set exit code in PS
Not that I'm aware of, sorry. The only thing that comes to mind is passing it via a text file and reading on a non-zero exit code event but that's an approach I think you are trying to avoid.
@user978511 I tried your version and it didn't catch my 1 / $null exception. VBscript received a 0 from the WshShell Run method. BTW $LASTEXITCODE is only set by executables such as ping.exe so your script would have to call one for it to work.
To transmit a message, cheat a bit. Use a standard error code for an exit code (i.e. 0x80070005 for Access Denied). Convert the exit code to hex, chop off the first four chars, and then run net helpmsg to spit out a helpful message. To explore messages, use the range operator and [Runtime.InteropServices.Marshal]::GetExceptionForHR, i.e. 0x80070001..0x80073B77 | ForEach-Object { [Runtime.InteropServices.Marshal]::GetExceptionForHR($_) } There are a LOT of built in errors. One of them will be close enough for your users to understand.

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.