Combining PowerShell And VBScript

by May 5, 2009

PowerShell has a great way of integrating existing VBScripts. All you need to do is call the script using the console-based host cscript.exe. Then, everything your VBScript returns via WScript.Echo is output to PowerShell.

Open an editor and type in the following BLOCKED SCRIPT

Do
value = InputBox("Please enter text! Empty text will abort.")
If value = "" Then
exit Do
End If

WScript.Echo value
Loop

Store the script as test.vbs. Next, call it from PowerShell like this (change the path accordingly):

cscript.exe 'C:UsersTobiastest.vbs'

The VBScript runs, and everything you enter is echoed back into your PowerShell session. Next, save the result from your VBScript into a variable:

$result = cscript.exe 'C:UsersTobiastest.vbs'

Again, your VBScript runs and everything you enter is stored in $result and can be used from PowerShell code.

Integration can even be real time. Simply, use your VBScript inside a pipeline like this:

cscript.exe 'C:UsersTobiastest.vbs' |
ForEach-Object { "processing input $_!" }

As you can see, the moment you enter something in your VBScript, the PowerShell pipeline picks it up and processes it. Let's create a more useful example. The next line expects input to be WMI classes and returns the WMI information from your local computer:

cscript.exe 'C:UsersTobiastest.vbs' |
ForEach-Object { Get-WMIObject $_ }

Try it: enter Win32_BIOS, or Win32_OperatingSystem. Any valid WMI class is acceptable. Of course, an error is generated if you enter something that is no WMI class name.