6

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?

Eric Furspan
  • 742
  • 3
  • 15
  • 36
  • 1
    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 Apr 29 '16 at 14:55
  • You can take a look at this ==> [Get Output of a PowerShell Script in a HTA](http://stackoverflow.com/questions/35198533/get-output-of-a-powershell-script-in-a-hta/35267951#35267951) – Hackoo Apr 29 '16 at 15:04

2 Answers2

12

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***';
Robbie Dee
  • 1,939
  • 16
  • 43
  • Sweet, that got it to return 50! Now does this only work with numeric values? I changed the exit to a string value and it doesn't work – Eric Furspan Apr 29 '16 at 15:04
  • 1
    Exit only supports integer return values but you could just grab the output. I've expanded my answer to demonstrate. – Robbie Dee Apr 29 '16 at 16:01
0

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.

Murrah
  • 1,508
  • 1
  • 13
  • 26