是否可以从 VBScript 运行 Powershell 代码?

Is it possible to run Powershell code from VBScript?

是否可以使用 VBScript 运行 Powershell 代码(不是 .ps1 文件)? 例如,在VBScript 下调用Powershell 函数(该脚本必须集成在VBScript 代码中)。 我知道如何使用 VBScript 执行外部 .ps1 脚本,但我没有找到任何有关集成的信息。 有任何想法吗? 谢谢

正如 Filburt 已经指出的那样,VBScript 无法执行 Powershell。但是,您可以做的是启动 Powershell 并将脚本作为参数传递。像这样,

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)

如果参数复杂,请考虑使用接受 Base64 编码命令的 -EncodedCommand。方便解决引号转义等问题。