calling VBScript from Powershell ..Is this right way to do it?

Viewed 41709

I have a VBscript file. I run this VBscript using CScript on windows 2012 server. The VBscript runs fine on the server.

But I need to call this VBScript file from Powershell. This is what I did.

For simplicity, this is what I have in my VBscript file

echo.vbs

Msgbox("hello world")

I wrote the test.ps1

    $acommand = "C:\Windows\System32\Cscript.exe C:\deleteit\echo.vbs"

    Invoke-Expression $acommand
2 Answers

It is the right way to run an external application and you can use the same technique if you are using command line exe's or VBS scripts.

Personally, I would be looking to add the functionality to a PowerShell script rather then calling an external VBS script, but that's just my 2 cents worth :)

Aside from simply running

Cscript.exe C:\deleteit\echo.vbs //nologo

There's a com object that can embed vbscript right into powershell, but it's 32-bit only. There's a way to run jobs as 32 bit. In powershell 7 you have to use the 32-bit version.

start-job {
  $sc = New-Object -ComObject MSScriptControl.ScriptControl.1
  $sc.Language = 'VBScript'
  $sc.AddCode('
    Function MyFunction(byval x)
      MyFunction = 2 * x
    End Function
  ')
  
  $sc.codeobject.MyFunction(1)
  $sc.codeobject.MyFunction(2)
} -runas32 | wait-job | receive-job

Output:

2
4
Related