Returning Text Information From PowerShell To VBScript

by | June 2,2009

Table of Contents

In a previous tip, you learned how to call PowerShell statements and read their return value. Return values are somewhat limited because they can only be numeric. There is an easy way to do this if you’d like to read more structured information from a PowerShell call and process the returned information within VBScript.

Reading PowerShell Output in VBScript Using WScript.Shell

From within VBScript, simply use the WScript.Shell object and take advantage of the Exec() method, which can read console output from another application.Exec() can read this information and returns it to VBScript since PowerShell outputs all results to its console.

pscommand = ” get-service | Foreach-Object { $_.Name } “
cmd = “powershell.exe -noprofile -command “ & pscommand

Set shell = CreateObject(“WScript.Shell”)
Set executor = shell.Exec(cmd)
executor.StdIn.Close
MsgBox executor.StdOut.ReadAll

In this example, VBScript uses PowerShell to return a list of service names. But, of course, you could use just any PowerShell statement in the pscommand variable.

Handling Console Output in VBScript with Exec()

Next, Exec() runs the PowerShell command. However, there is one gotcha before it can read the console output. PowerShell by default waits for console input before it returns anything. This is why you first have to close the input stream before you can use ReadAll() to retrieve the results.