【问题标题】:Is it possible to run Powershell code from VBScript?是否可以从 VBScript 运行 Powershell 代码?
【发布时间】:2017-06-22 16:11:44
【问题描述】:

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

【问题讨论】:

  • 不,这无法完成,因为 VBScript 解释器无法处理 PS 代码。可能是您的实际问题是将参数值从 VBScript 传递到外部 PS 脚本?
  • 感谢您的回答。不,我不想将参数传递给我的外部 ps 脚本。主要思想是使用一个脚本执行多个任务,但它应该是可读的(不是 .exe)。
  • 您可以从 VBS 调用“powershell -command”,技术上能够将该命令创建为脚本中的字符串。
  • 我认为,从 vb 调用 powershell 并传递参数,它将从外部 powershell 处理程序运行

标签: powershell vbscript integration


【解决方案1】:

正如 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。方便解决引号转义等问题。

【讨论】:

  • 但是如果我有 60 行的 Powershell 代码,我可以将它作为参数传递吗?
  • @VictorVasilyonok 至少你可以在命令中抛出一个破折号并通过标准输入将你的 60 行传输到 Powershell。同样在编码命令的情况下,答案是正确的。
  • @VictorVasilyonok VBScript 可以将 PS1 文件写入磁盘然后运行它。将实际脚本存储在集中式网络共享上并使用 VBScript 复制和/或执行这些脚本怎么样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
相关资源
最近更新 更多