Reading PowerShell Return Values From VBScript

by Jun 1, 2009

It is easy for VBScript to call a PowerShell script as you have learned in a previous tip. PowerShell can even return a numeric value so your VBScript knows if all went fine.

Here is a short example that does not even call an external PowerShell script, but instead supplies the PowerShell code directly. The PowerShell code looks like this:

$rv = read-host 'Enter return value (numeric value)'$rv

In this example, PowerShell simply asks you interactively for the numeric return code it should return. Your PowerShell code could be much more sophisticated in production scripts and return a value based on success or failure. You can even replace the PowerShell code with a path to an external PowerShell script (just make sure you have set the execution policy correctly because by default, PowerShell does not run scripts). Also, you'll want to explicitly hand over the return code that is returned from the script back to the caller like this:

pscommand = ".test1.ps1; exit $LASTEXITCODE"

Next, the script appends the call to powershell.exe as described previously in another tip. Then, VBScript is ready to run your command using the WScript.Shell object and its Run() method.

pscommand = "$rv = read-host 'Enter return value (numeric value)'; exit $rv"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
rv = shell.Run(cmd, , True)
MsgBox "PowerShell returned: " & rv, vbSystemModal

Make sure you use Run() synchronously by specifying True as third argument to read the value PowerShell returned. This way, Run() waits for the PowerShell command to complete and returns the value PowerShell has handed over to EXIT.