Powershell脚本始终通过HTA返回0

时间:2016-09-05 10:05:31

标签: powershell vbscript hta

我正在尝试从我编写的PowerShell脚本中获取输出。

test.ps1

Get-Process

HTA中的VBScript编码如下:

Sub Test()  
    cmd = "powershell.exe -noprofile -command .\test.ps1; exit $LASTEXITCODE"
    Set shell = CreateObject("WScript.Shell")
    Set executor = shell.Exec(cmd)
    executor.StdIn.Close
    MsgBox executor.StdOut.ReadAll
End Sub

当我在命令行中尝试使用此cmd字符串时,它会更好地工作。但是消息框总是弹出空白区域。

解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

最有可能test.ps1不驻留在VBScript运行的工作目录中,因此找不到它,因此不会执行。如果在同一目录中有VBScript和PowerShell脚本,则最好从VBScript路径构建PowerShell脚本路径:

Set fso = CreateObject("Scripting.FileSystemObject")
dir = fso.GetParentFolderName(WScript.ScriptFullName)
psscript = fso.BuildPath(dir, "test.ps1")

然后你可以像这样构建命令字符串:

cmd = "powershell.exe -NoProfile -File """ & psscript & """"

额外的双引号用于处理路径中的空格。我还建议使用参数-File而不是复杂的-Command "...; exit $LASTEXITCODE"

作为替代方案(如果您希望坚持从当前工作目录运行PowerShell脚本),您还可以更改脚本中的目录:

Set fso = CreateObject("Scripting.FileSystemObject")
Set sh  = CreateObject("WScript.Shell")

sh.CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName)

...
cmd = "powershell.exe -NoProfile -File .\test.ps1"

编辑: HTA与常规VBScripts具有不同的运行时环境。 HTA引擎不提供WScript对象,因此WScript.ScriptFullName在HTA中不起作用。但是,您可以从文档位置确定脚本目录:

Set fso = CreateObject("Scripting.FileSystemObject")
dir = fso.GetParentFolderName(Replace(document.location.href, "file:///", ""))
psscript = fso.BuildPath(dir, "test.ps1")

如果要将路径分隔符规范化为反斜杠,可以这样做:

psscript = fso.BuildPath(Replace(dir, "/", "\"), "test.ps1")

或者像这样:

psscript = fso.BuildPath(fso.GetFolder(dir).Path, "test.ps1")

答案 1 :(得分:1)

在这个问题中讨论了同样的问题: Get Output of a PowerShell Script in a HTA

解决方案是将powershell脚本中的输出写入文本文件,并在HTA中读取该文本文件的输出并使用MsgBox显示它。

也许这也是你的解决方案。