gpt4 book ai didi

powershell - 有响应的Powershell脚本,没有窗口?

转载 作者:行者123 更新时间:2023-12-02 23:53:10 25 4
gpt4 key购买 nike

我想在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
}

最佳答案

注意:正如您所发现的那样,将AHK(AutoHotkey)与外部PowerShell进程配合使用不适合必须每25毫秒运行一次的任务,这会产生过多的处理开销。
如果只需要获取目录列表,则可以使用 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

    关于powershell - 有响应的Powershell脚本,没有窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53359613/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com