5
votes

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?

2
I think 0 is the exit code of powershell execution, stand for success. Seems your return pulled the status of the execution. You can do exit 50 in powershell but I don't think this is the legit way of doing things. - Kai Zhao
You can take a look at this ==> Get Output of a PowerShell Script in a HTA - Hackoo

2 Answers

11
votes

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***';
0
votes

As a followup, using the VBScript above to output a string. In your PS script if you use eg

write-host "Error: some specific thing happened"

to set various error or success messages the

MsgBox executor.StdOut.ReadAll

will display all of what you write via write-host.

A helpful way to display the outcome of the PS script to your VBA user.

Just FYI.