Search code examples
cmdcomautohotkey

CMD/ComObject: why this CMD window has zero content?


I'm working on an autohotkey script which runs some CMD command. Considering other factors, at last I have to do it with ComObject, which I did not learn before. But at the end of the day this question is about CMD command.

abc is a varible string of 3 lines, standing for 3 commands. This code will run these 3 commands then exit. Please take a look: Originally it's "exec := shell.Exec(ComSpec " /Q /K echo off")", so cmd window is totally hidden, so I changed it to " /K echo on", now I can see CMD window, with a title, and all 3 commands ran successfully, but in the whole process there's no text in this CMD window. How can I fix it?

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()
}

Solution

  • So, what I think you're trying to do, is to get a cmd to appear with the output of your commands?
    That example function from the AHK documentation you're using is for just reading the output of your command(s), and it successfully does that.

    I think this is was you want:
    Run, % A_ComSpec " /K echo Hello!"
    (Run, %ComSpec% /K echo Hello! in legacy AHK)

    For chaining more commands together, you can wrap them in " and use & (I'm no cmd expert, so not sure if & can be used in every case, but yeah):

    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!""
    )"
    

    A continuation section is used there to break it into multiple lines and be more readable.
    Same thing here without a 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!"""
    

    Or in legacy AHK:

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

    And if it's important to have it as a function, something like this would do the trick

    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", "&") """"
    }
    

    So replace line breaks with an &.