我想在PowerShell中运行命令并在AutoHotkey中使用响应。我已经找到了很多有关如何运行PowerShell脚本的信息,但是没有人说我如何在AutoHotkey中使用它的响应。
我已经尝试过了:
MsgBox % ComObjCreate("WScript.Shell").Exec("powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -noProfile -nologo dir").StdOut.ReadAll()
但是这仍然在很短的时间内闪烁了一个窗口。我每25毫秒循环一次此命令,因此让窗口闪烁通常不是有效的解决方案。
编辑:
最终得到了最简单的解决方案:
cmd = powershell.exe -command "(Get-Process -Id " %pid% ").Threads[1].WaitReason"
shell := setup()
Loop {
string := shell.exec(cmd).stdout.readall()
...}
setup() {
detecthiddenwindows on
run %comspec% /k ,, hide useerrorlevel, pid
winwait ahk_pid %pid%,, 10
DllCall("AttachConsole", "uint", pid)
con := DllCall("CreateFile"
, "str", "CONOUT$", "uint", 0xC0000000, "uint", 7, "uint", 0, "uint", 3, "uint", 0, "uint", 0)
oshell := comobjcreate("wscript.shell")
return oshell
}
答案 0 :(得分:1)
注意:正如您所发现的那样,将AHK(AutoHotkey)与外部PowerShell进程配合使用不适合必须每25ms运行一次的任务,因为这样做您会发现自己-这样做的处理开销太大。 />
如果只需要获取目录列表,则可以使用Loop
command for files-参见this answer使用内置的AHK功能来做到这一点。
下面的解决方案通常演示如何运行控制台程序:
来自AHK。
您不能使用ComObjCreate("WScript.Shell").Exec()
运行控制台应用程序隐藏。
相反,虽然可以使用RunWait
进行隐藏运行,但是不能使用它来捕获(控制台)输出。
解决方法用于:
使用RunWait
。
向控制台程序调用中添加对(临时)文件的输出重定向。
然后用FileRead
读取该文件的内容(并删除临时文件)。
; Get a temporary file path
tempFile := A_Temp "\" DllCall("GetCurrentProcessId") ".txt" ; "
; Run the console program hidden, redirecting its output to
; the temp. file (with a program other than powershell.exe or cmd.exe,
; prepend %ComSpec% /c; use 2> to redirect error output), and wait for it to exit.
RunWait, powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -noProfile dir > %tempFile%,, Hide
; Read the temp file into a variable and then delete it.
FileRead, content, %tempFile%
FileDelete, %tempFile%
; Display the result.
MsgBox % content