是否可以从VBScript运行Powershell代码? [英] Is it possible to run Powershell code from VBScript?

查看:136
本文介绍了是否可以从VBScript运行Powershell代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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)

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

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

这篇关于是否可以从VBScript运行Powershell代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆