Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return PowerShell variable to VBScript

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?

like image 465
Eric Furspan Avatar asked Apr 29 '16 14:04

Eric Furspan


People also ask

Can PowerShell script return a value?

The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

What is $_ in PowerShell script?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

Why we use $_ in PowerShell?

$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object . But it can be used also in other types of expressions, for example with Select-Object combined with expression properties.

What is $() in PowerShell?

Subexpression operator $( ) Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.


1 Answers

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***';
like image 53
Robbie Dee Avatar answered Sep 19 '22 18:09

Robbie Dee