我试图将HTML应用程序[HTA]中的powershell脚本称为:
Set WshShell = CreateObject("WScript.Shell")
Set retVal = WshShell.Exec("powershell.exe C:\PS_Scripts\test.ps1")
test.ps1只返回进程计数
return (Get-Process).Count
我想获取此powershell脚本的输出,然后将其存储在本地变量中或显示在HTA上。怎么办呢?
我尝试使用:
retVal.StdIn.Close()
result = retVal.StdOut.ReadAll()
alert(result)
但打印结果值为空。
请帮我解决这个问题。
答案 0 :(得分:4)
这对我有用:
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>
答案 1 :(得分:3)
这是另一个示例,说明如何在使用HTA执行powhershell文件时在textarea中获取输出结果!
<html>
<head>
<title>Execution a powershell file with HTA by Hackoo</title>
<HTA:APPLICATION
APPLICATIONNAME="Execution a powershell file with HTA by Hackoo"
SCROLL="yes"
SINGLEINSTANCE="yes"
WINDOWSTATE="maximize"
ICON="Winver.exe"
SCROLL="no"
/>
<script language="VBScript">
Option Explicit
Sub Run_PS_Script()
ExampleOutput.value = ""
btnClick.disabled = True
document.body.style.cursor = "wait"
btnClick.style.cursor = "wait"
Dim WshShell,Command,PSFile,return,fso,file,text,Temp
Set WshShell = CreateObject("WScript.Shell")
Temp = WshShell.ExpandEnvironmentStrings("%Temp%")
Command = "cmd /c echo Get-WmiObject Win32_Process ^| select ProcessID,ProcessName,Handle,commandline,ExecutablePath ^| Out-File %temp%\output.txt -Encoding ascii > %temp%\process.ps1"
PSFile = WshShell.Run(Command,0,True)
return = WshShell.Run("powershell.exe -ExecutionPolicy Unrestricted -File %temp%\process.ps1", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile(Temp &"\output.txt", 1)
text = file.ReadAll
ExampleOutput.Value=text
file.Close
document.body.style.cursor = "default"
btnClick.style.cursor = "default"
btnClick.disabled = False
End Sub
</script>
</head>
<body bgcolor="123456">
<textarea id="ExampleOutput" style="width:100%" rows="37"></textarea>
<br>
<center><input type="button" name="btnClick" value="Run powershell script file " onclick="Run_PS_Script()"></center>
</body>
</html>
答案 2 :(得分:0)
您可以使用WScript.Shell的1
方法来避免中间文件。不幸的是,它在运行时会打开一个新窗口,但是代码更加简洁,使您可以访问StdOut和StdErr流。将其粘贴到.HTA文件中(如果需要,可以包含标头和正文)进行测试:
V1
部分问题可能是Exec没有阻止StdOut开始填充。添加计时器可以为我解决该问题。