1

Is it possible to run Powershell code (not .ps1 file) using VBScript? For example, to call Powershell function under VBScript (this script must be integrated in VBScript code). How to execute external .ps1 script using VBScript I know, but I didn't find any information about integration. Any ideas? Thanks

4
  • 1
    No, this cannot be done because the VBScript interpreter cannot handle PS code. Could it be that your actual issue is passing parameter values from your VBScript to your external PS script? Commented Jun 22, 2017 at 7:53
  • Thank you for your answer. No, I don't want to pass paramaters to my external ps script. The main idea is to use one script for multiple tasks, but it should be readable (not .exe). Commented Jun 22, 2017 at 8:04
  • You can call "powershell -command" from VBS, technically being able to create that command as a string in your script. Commented Jun 22, 2017 at 8:05
  • I think,call a powershell from vb and pass parameters,it would be run from external powershell handler Commented Jun 22, 2017 at 8:07

1 Answer 1

3

As Filburt already noted, VBScript cannot execute Powershell as such. What you can do, however, is to launch Powershell and pass script as a parameter. Like so,

option explicit

Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2

Dim objShell, oExec, strOutput, strPS1Cmd

' Store the ps1 code in a variable
strPS1Cmd = "& { get-date }"

' Create a shell and execute powershell, pass the script    
Set objShell = wscript.createobject("wscript.shell")
Set oExec = objShell.Exec("powershell -command """ & strPS1Cmd & """ ")

Do While oExec.Status = WshRunning
     WScript.Sleep 100
Loop

Select Case oExec.Status
   Case WshFinished
       strOutput = oExec.StdOut.ReadAll()
   Case WshFailed
       strOutput = oExec.StdErr.ReadAll()
 End Select

WScript.Echo(strOutput)

In case of complex arguments, consider using the -EncodedCommand that accepts Base64 encoded command. Handy to work around quote escapes and such.

Sign up to request clarification or add additional context in comments.

3 Comments

But if I have Powershell code for 60 lines, can I pass It as parameter?
@VictorVasilyonok At least you can throw a single dash in command and pipe your 60 lines via stdin to Powershell. Also in case of encoded command the answer is true.
@VictorVasilyonok VBScript could write the PS1 file onto disk and then run it. How about storing the actual scripts on a centralized network share and use VBScript to copy and/or execute those?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.