Calling VBScript From PowerShell

by Jun 3, 2009

Sometimes, you may have an existing VBScript that already does just what you want. You can easily incorporate any VBScript into PowerShell because PowerShell can call just about anything that is executable, including VBScript. The tricky part is that you mainly want the VBScript to not just do something, but also to report back success or failure. Here is an approach on how to do just that.

First, take a look at this simple BLOCKED SCRIPT

answer = MsgBox(“Do you use PowerShell yet?”,
vbYesNo + vbQuestion, “Survey”)
if answer = vbYes then
WScript.Quit 1
elseif answer = vbNo then
WScript.Quit 2
end if

It simply pops up a dialog and asks a question. Based on the answer, VBScript returns different numeric return codes using WScript.Quit. Save this as client.vbs.

Next, let’s check out how PowerShell can call the VBScript and read back its return value:

cscript.exe c:…path_to_scriptclient.vbs
switch ($LASTEXITCODE) {
1 {“That’s great!”}
2 {“It is worth it though!”}
default {“Unexpected return value…”}
}

The important part is to call the VBScript explicitly using cscript.exe and not the default wscript.exe. Only the console-based script host cscript.exe can process return values. Once PowerShell has called the VBScript, it can then retrieve its return value in the automatic variable $LASTEXITCODE. This is true for any external application or script PowerShell calls and is the equivalent to ERRORLEVEL in batch files.