【问题标题】:CMD/ComObject: why this CMD window has zero content?CMD/ComObject:为什么这个 CMD 窗口的内容为零?
【发布时间】:2021-03-02 09:12:59
【问题描述】:

我正在编写一个运行某些 CMD 命令的自动热键脚本。考虑到其他因素,最后还是得用之前没学过的ComObject来做。但归根结底,这个问题是关于 CMD 命令的。

abc 是一个 3 行的变量字符串,代表 3 个命令。此代码将运行这 3 个命令然后退出。 请看一下:原来是"exec := shell.Exec(ComSpec " /Q /K echo off")",所以cmd窗口是完全隐藏的,所以我把它改成了" /K echo on",现在可以看到了CMD 窗口,有标题,3 个命令全部运行成功,但在整个过程中,这个 CMD 窗口中没有任何文字。我该如何解决?

abc := "xxxxxx"
RunWaitMany(abc)
RunWaitMany(commands) {
    shell := ComObjCreate("WScript.Shell")
    ; Open cmd.exe with echoing of commands disabled
    exec := shell.Exec(ComSpec " /K echo on")
    ; Send the commands to execute, separated by newline
    exec.StdIn.WriteLine(commands "`nexit")  ; Always exit at the end!
    ; Read and return the output of all commands
    return exec.StdOut.ReadAll()
}

【问题讨论】:

  • 嗯。 exit 关闭 cmd 进程。你这样做ReadAll之后。 AHK 真的能够从不再存在的进程中读取任何内容吗?
  • @Stephan 退出并不意味着 com 对象不再存在。该代码按预期工作,实际上是 AHK 文档中示例的直接复制粘贴。我认为 OP 只是想把错误的东西用于他想要的东西。

标签: cmd com autohotkey


【解决方案1】:

那么,我认为您想要做的是让 cmd 出现在您的命令输出中?
您正在使用的 AHK 文档中的示例函数仅用于读取命令的输出,并且它成功地做到了。

我想这就是你想要的:
Run, % A_ComSpec " /K echo Hello!"
(旧版 AHK 中的Run, %ComSpec% /K echo Hello!

为了将更多命令链接在一起,您可以将它们包装在 " 中并使用 &(我不是 cmd 专家,所以不确定 & 是否可以在每种情况下都使用,但是是的):

Run, % A_ComSpec "
(Join
 /K ""echo Hi, lets list the IPv4 addresses in the ipconfig command.
& ipconfig | findstr IPv4 
& echo Sweet, it worked 
& echo Bye!""
)"

continuation section 用于将其分成多行并更具可读性。
同样的事情没有延续部分:

Run, % A_ComSpec " /K ""echo Hi, lets list the IPv4 addresses in the ipconfig command. & ipconfig|findstr IPv4 & echo Sweet, it worked & echo Bye!"""

或者在旧版 AHK 中:

Run, %ComSpec% /K "echo Hi`, lets list the IPv4 addresses in the ipconfig command. & ipconfig|findstr IPv4 & echo Sweet`, it worked & echo Bye!"

如果把它作为一个函数很重要,这样的事情就可以解决问题

MyCommands := "
(Join`n
echo Hi, lets list the IPv4 addresses in the ipconfig command.
ipconfig | findstr IPv4 
echo Sweet, it worked 
echo Bye!
)"

RunCommands(MyCommands)
return

RunCommands(commands)
{
    Run, % A_ComSpec " /K """ RegExReplace(commands, "`r?`n", "&") """"
}

所以用&替换换行符。

【讨论】:

  • 非常感谢您的详细解释。正如您所提到的,“运行”在这里是正确的。我用你的代码进行了全面测试,我学到的最后一课是:将值(用 & 分隔的多个命令)设置为一个字符串,然后在运行中使用这个字符串。这样,在设置值时,我还可以在字符串中包含一些其他变量。
猜你喜欢
  • 1970-01-01
  • 2022-09-24
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多