How to return PowerShell variable to VBScript

Eric Furspan picture Eric Furspan · Apr 29, 2016 · Viewed 9.2k times · Source

I have a vbscript to call a PowerShell script in hopes of returning the PowerShell output to an HTA (HTML Application) GUI. Right now I just want to see if I can return the PowerShell output into a MsgBox in the vbscript. I am not having much luck with this.

VBScript Code:

Set shell = CreateObject("WScript.Shell")
return = shell.Run("powershell.exe -executionpolicy bypass -noprofile -file pathToScript\PowerShellToVBA.ps1", , true)
MsgBox return

PowerShell Code:

Clear-Host
return 50

I am trying to keep the return value extremely simple until it works. With this, I would expect the MsgBox to return '50', however it is returning '0' instead. Any ideas what im doing wrong?

Answer

Robbie Dee picture Robbie Dee · Apr 29, 2016

I think you just want the exit command to get the return value:

VBScript

pscommand = ".\myscript.ps1; exit $LASTEXITCODE"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
rv = shell.Run(cmd, , True)
MsgBox "PowerShell returned: " & rv, vbSystemModal

Powershell

exit 50;

EDIT #1

Or if you want to grab a return string:

VBScript

pscommand = ".\myscript2.ps1"
cmd = "powershell.exe -noprofile -command " & pscommand
Set shell = CreateObject("WScript.Shell")
Set executor = shell.Exec(cmd)
executor.StdIn.Close
MsgBox executor.StdOut.ReadAll

Powershell

Write-Output '***SUCCESS***';