1

I'm trying to get an output from the PowerShell script that I wrote.

test.ps1

Get-Process

the VBScript in the HTA is coded as following:

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

When I'm trying this cmd string in the command line it works perferctly. But the message box is always popping up with empty space.

What's the best way to fix this?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

2 Answers2

1

Most likely test.ps1 doesn't reside in the working directory of the VBScript run, so it isn't found and thus not executed. If you have VBScript and PowerShell script in the same directory it's best to build the PowerShell script path from the VBScript path:

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

Then you can build the command string like this:

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

The additional double quotes are to take care of spaces in the path. I also recommend using the parameter -File instead of the convoluted -Command "...; exit $LASTEXITCODE".


As an alternative (if you want to stick with running the PowerShell script from the current working directory) you could also change the directory in your script:

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

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

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

Edit: HTAs have a different runtime environment than regular VBScripts. The HTA engine doesn't provide a WScript object, so WScript.ScriptFullName doesn't work in HTAs. You can, however, determine the script directory from the document location:

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

If you want to canonicalize path separators to backslashes you can do it either like this:

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

or like this:

psscript = fso.BuildPath(fso.GetFolder(dir).Path, "test.ps1")
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
1

In this question the same problem was discussed: Get Output of a PowerShell Script in a HTA

The solution was to write the output in your powershell script to a text file and in the HTA read the output from that text file and display it with a MsgBox.

Maybe this is a solution for you too.

Community
  • 1
  • 1
A189198
  • 396
  • 2
  • 7