Is it possible to run Powershell code from VBScript?

夙愿已清 提交于 2020-07-05 05:12:51

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44693317/is-it-possible-to-run-powershell-code-from-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!