Search code examples
command-promptautoit

Command prompt and AutoIt/StdinWrite


I wanted to study and understand the StdinWrite function and so wrote the following piece of code.

I want to write data to the prompt, read the output, write the data again and then read the output again. Here is the code I have written. The first MsgBox display is correct, but the second is blank! Why?

    #include <Constants.au3>
    $pid = Run("C:\Windows\system32\cmd.exe",@SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD)
    StdinWrite($pid,"cd ")
    StdinWrite($pid,"C:\users\test1")
    StdinWrite($pid,@CRLF)
    StdinWrite($pid)
    Local $data
    While True
        $data &= StdoutRead($pid)
        If @error Then
            MsgBox(0,"","error")
            ExitLoop
        EndIf

    WEnd
    MsgBox(0, "Debug", $data)
    StdinWrite($pid,"cd ")
    StdinWrite($pid,"C:\users\test2")
    StdinWrite($pid,@CRLF)
    StdinWrite($pid)
    $data = ""
    While True
        $data &= StdoutRead($pid)
        If @error Then
            MsgBox(0,"","error")
            ExitLoop
        EndIf

    WEnd
    MsgBox(0, "Debug", $data)
Sleep(10000)
Exit

Update: Based on the comments by user2097265. I have modified the above code to the one below. I have shown the output below. Instead of ConsoleWrite I am using Cout in Console.au3. The second set of commans don't appear to have worked.

#include <Constants.au3>
#include <Console.au3>
$pid = Run("C:\Windows\system32\cmd.exe",@SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD)
StdinWrite($pid,"cd ")
StdinWrite($pid,"C:\users\test1")
StdinWrite($pid,@CRLF)
Local $data
Sleep(2000)
$data &= StdoutRead($pid)
;ConsoleWrite("Debug:" & $data & @LF)
Cout( $data & @LF)
$data = ""
StdinWrite($pid,"cd ")
StdinWrite($pid,"C:\users\test2")
StdinWrite($pid,@CRLF)
StdinWrite($pid,@CRLF)
StdinWrite($pid,@CRLF)
StdinWrite($pid)
$data &= StdoutRead($pid)
;ConsoleWrite("Debug:" & $data & @LF)
Cout( $data & @LF)
MsgBox(0,"","Close")

Here is the output:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>cd C:\users\test1

C:\Users\test1>
cd C:\users\test2

Solution

  • Your code is fine; just needs Sleep before the second StdoutRead as well, to give it time to return. I didn't use <Console.au3> though.

    To display possible errors use $data &= StdoutRead($pid) & StderrRead($pid) instead.