Get Output of a PowerShell Script in a HTA

shanky picture shanky · Feb 4, 2016 · Viewed 7.3k times · Source

I am trying to call a powershell script from HTML Application [HTA] as :

Set WshShell = CreateObject("WScript.Shell")

Set retVal = WshShell.Exec("powershell.exe  C:\PS_Scripts\test.ps1")

Where the test.ps1 just has the process count returning

return (Get-Process).Count

I want to get the output of this powershell script and then store it in a local variable or display on HTA. How can this be done ?

I tried using :

retVal.StdIn.Close()

result = retVal.StdOut.ReadAll()


alert(result)

But the printed result value is null.

Please help me how to achieve this.

Answer

Marc picture Marc · Feb 4, 2016

This works for me:

test.ps1:

(Get-Process).Count | Out-File c:\temp\output.txt -Encoding ascii

test.hta:

<head>
<title>HTA Test</title>
<HTA:APPLICATION 
     APPLICATIONNAME="HTA Test"
     SCROLL="yes"
     SINGLEINSTANCE="yes"
     WINDOWSTATE="maximize"
</head>
<script language="VBScript">
    Sub TestSub

        Set WshShell = CreateObject("WScript.Shell")
        return = WshShell.Run("powershell.exe -ExecutionPolicy Unrestricted -File test.ps1", 0, true)
        Set fso  = CreateObject("Scripting.FileSystemObject")
        Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
        text = file.ReadAll     
        alert(text)     
        file.Close      
    End Sub
</script>
<body>
    <input type="button" value="Run Script" name="run_button"  onClick="TestSub"><p> 
</body>