Jump to content
fopetesl

Command Prompt batch file fails

Recommended Posts

fopetesl

I have several batch files, e.g.

echo off
    echo !DT | ncat 192.168.1.6 80 > scan1.dta

This data1.bat works as expected by saving data from !DT command.

I have tried several variations from AutoIt

;  $DOS = RunWait(@ComSpec & " /k " & "ncat 192.168.1.6 80 <getdata >scan1.dta", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
;  $DOS = Run(@ComSpec & " /k " & "ncat 192.168.1.6 80 <getdata >scan1.dta", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
;  $DOS = Run(@ComSpec & " /c " & "echo ?DT | ncat 192.168.1.6 80 > scan1.dta & @CRLF", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
  $DOS = Run(@ComSpec & " /c " & "data1.bat & @CRLF", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)

but none save the data to scan1.dta

Run out of ideas so far...

 

Edited by fopetesl
Missing code

The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
Jos

Are you sure you are looking in the right subdirectory ?
Why do you have the @CRLF in there ? You don't need to give a Enter when running a script!

Run it as test like this and see what directory it is in and whether there is an error:

$DOS = Run(@ComSpec & " /k " & "data1.bat", "", default, $STDERR_CHILD + $STDOUT_CHILD)

Jos


Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
fopetesl

No change, Jos.

Not sure what you mean by "see what directory it is in" since although the command prompt windows flashes up it isn't long enough to take note.

I can see that the scan1.dta files has been opened since the timestamp has been updated but it contains no data.

I also did a search of the whole drive in case scan1.dta was placed somewhere else.

 


The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
fopetesl

Still the same, Jos. syntax as you suggested:

  $DOS = Run(@ComSpec & " /k " & "data1.bat", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)


The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
JLogan3o13

The /k should keep the command window open, does it? If so, which directory is it showing? "Still the same" is not answering the question that Jos has asked twice now.

Edited by JLogan3o13

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites
Jos
15 minutes ago, fopetesl said:

Still the same, Jos. syntax as you suggested:

  $DOS = Run(@ComSpec & " /k " & "data1.bat", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)

This is NOT the commandline I provide!  Check for the difference.

Jos

Edited by Jos

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
fopetesl

Sorry. Too many balls in the air.

No. Windows does not stay open even with corrected syntax.

$DOS = Run(@ComSpec & " /k " & "data1.bat", "", default, $STDERR_CHILD + $STDOUT_CHILD)

Edited by fopetesl
add code

The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
MattHiggs
31 minutes ago, fopetesl said:

Sorry. Too many balls in the air.

No. Windows does not stay open even with corrected syntax.

 

$DOS = Run(@ComSpec & " /k " & "data1.bat", "", default, $STDERR_CHILD + $STDOUT_CHILD)

 

Well part of the problem that I believe that @Jos is trying to get to is that you are not specifying the directory in which the file is located.  The only case in which you wouldn't have to is if the script that you are running is in the same directory as the file you are trying to interact with.  If it is not, then that would be the issue: the script has no idea where the file is, because it is only looking in the current working directory (aka the directory in which the script is located).  You need to specify where the file is located in the "working Directory parameter.  Using the code you provided:

$DOS = Run(@ComSpec & " /k " & "data1.bat", "Path\To\Folder\Containing\file", default, $STDERR_CHILD + $STDOUT_CHILD)

Share this post


Link to post
Share on other sites
Jos

The simple point I am getting to is that I think the CMD prompt should stay open when /k is used so you can see any error and the workdir it is in.

When that is not the case try an even simpler version to understand some of the basics:

$DOS = Run(@ComSpec & " /k " & "data1.bat")

Jos


Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
BrewManNH

Is there any reason, other than having to rewrite them, that you can't get rid of the batch files entirely and just do everything with AutoIt?


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
Jos

A quick test revealed indeed that nothing was shown with the STDERR and STDOUT parameters. These 2 give the same result and show me an error message.
The first one as console output and the second in the CMD prompt:

#include <AutoItConstants.au3>
$DOS = Run(@ComSpec & " /k " & "data1.bat", "", default, $STDERR_CHILD + $STDOUT_CHILD)
; Wait until the process has closed using the PID returned by Run.
ProcessWaitClose($DOS)
; Read the Stdout stream of the PID returned by Run. This can also be done in a while loop. Look at the example for StderrRead.
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : StdoutRead($iPID) = ' & StdoutRead($DOS) & @CRLF ) ;### Debug Console
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : StdoutRead($iPID) = ' & StderrRead($DOS) & @CRLF ) ;### Debug Console
;
$DOS2 = Run(@ComSpec & " /k " & "data1.bat")

Jos

  • Like 1

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
fopetesl

MattHiggs, I tried your suggestion some while back which didn't resolve the issue.

note also

Global $BatchDir = "C:\ncat\"

is at top of file.

BrewMan. I'd love to include these in my script but my tiny brain can't figure out how to pipe commands to ncat.exe and collect any return data.  Oddly though some .bat files do work and send a response I'd expect, e.g.

Run(@ComSpec & " /k " & "IsHome.bat", "", @SW_HIDE)
         Sleep(400)
         Local $hFileOpen = FileOpen("homerep", $FO_BINARY)
         Local $sFileRead = FileRead($hFileOpen)
         FileClose($hFileOpen)
         Local $sStr = StringTrimLeft(StringToBinary("?HMO"), 4)
         If StringInStr($sFileRead, $sStr) Then
           MsgBox(0, "", "Head Home", 2)
           return(0)
         EndIf 

This just checks the (same) machine earlier in the script for scanning head at 'home' position.

The only difference I can see between the working script and the failure is the amount of data returned.  "?HMO" returns eight characters, data1.bat returns 754 hex bytes which it does from command prompt but just creates an empty file from AutoIt.

Jos, I'll get to your read output/errors in a while, (I hope), still have balls in the air.

 


The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
MattHiggs
9 hours ago, fopetesl said:

MattHiggs, I tried your suggestion some while back which didn't resolve the issue.

note also

Global $BatchDir = "C:\ncat\"

is at top of file.

BrewMan. I'd love to include these in my script but my tiny brain can't figure out how to pipe commands to ncat.exe and collect any return data.  Oddly though some .bat files do work and send a response I'd expect, e.g.

 

Run(@ComSpec & " /k " & "IsHome.bat", "", @SW_HIDE)
         Sleep(400)
         Local $hFileOpen = FileOpen("homerep", $FO_BINARY)
         Local $sFileRead = FileRead($hFileOpen)
         FileClose($hFileOpen)
         Local $sStr = StringTrimLeft(StringToBinary("?HMO"), 4)
         If StringInStr($sFileRead, $sStr) Then
           MsgBox(0, "", "Head Home", 2)
           return(0)
         EndIf

This just checks the (same) machine earlier in the script for scanning head at 'home' position.

The only difference I can see between the working script and the failure is the amount of data returned.  "?HMO" returns eight characters, data1.bat returns 754 hex bytes which it does from command prompt but just creates an empty file from AutoIt.

Jos, I'll get to your read output/errors in a while, (I hope), still have balls in the air.

 

So are you setting $batchdir as the working directory in the run function?

$DOS = Run(@ComSpec & " /k " & "data1.bat", $batchdir, default, $STDERR_CHILD + $STDOUT_CHILD)

If this is the case, you need to get rid of the last "\" so that $batchdir = "C:\ncat"

when you put the last "\" at the end of the directory path, the variable no longer equals the parent directory.

Share this post


Link to post
Share on other sites
fopetesl

MattHiggs. VERY carefully followed your suggestions.

No change. Still have empty scan1.dta but file timestamp is updated to current.

Same applies to RunWait() except it takes several seconds before Command Prompt window flashes very briefly before returning to GUI Tab.

So the .dta file is clearly opened and closed without having data written.

What is the difference between Run() and ShellExecute()?

 


The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
anthonyjr2
3 hours ago, fopetesl said:

What is the difference between Run() and ShellExecute()?

ShellExecute() runs a program with its default interpreter. For example executing a word document would automatically open Microsoft Word. Run is usually used to run more specific programs with an exact path. They are very similar but can have slightly different use cases. I've also heard that Run is generally faster because it doesn't have to go through a separate API. If you want some more information I found this thread that explains it some more.


UHJvZmVzc2lvbmFsIENvbXB1dGVyZXI=

Share this post


Link to post
Share on other sites
Jos
On 2017-6-5 at 5:35 PM, fopetesl said:

Jos, I'll get to your read output/errors in a while, (I hope), still have balls in the air.

....  and? 


Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
fopetesl
On 05/06/2017 at 3:25 PM, Jos said:

A quick test revealed indeed that nothing was shown with the STDERR and STDOUT parameters. These 2 give the same result and show me an error message.
The first one as console output and the second in the CMD prompt:

#include <AutoItConstants.au3>
$DOS = Run(@ComSpec & " /k " & "data1.bat", "", default, $STDERR_CHILD + $STDOUT_CHILD)
; Wait until the process has closed using the PID returned by Run.
ProcessWaitClose($DOS)
; Read the Stdout stream of the PID returned by Run. This can also be done in a while loop. Look at the example for StderrRead.
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : StdoutRead($iPID) = ' & StdoutRead($DOS) & @CRLF ) ;### Debug Console
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : StdoutRead($iPID) = ' & StderrRead($DOS) & @CRLF ) ;### Debug Console
;
$DOS2 = Run(@ComSpec & " /k " & "data1.bat")

Jos

Jos, not sure what I actually see

>"C:\Program Files (x86)\AutoIt3\SciTE\..\autoit3.exe" /ErrorStdOut "C:\S3_GUI\HauterS3 with_Tabs1.au3"    
@@ Debug(211) : StdoutRead($iPID) =
C:\ncat>echo off
    C:\ncat>
@@ Debug(212) : StdoutRead($iPID) = Ncat: .
    >Exit code: 0    Time: 34.01

It's clear that the 2nd Run() $DOS2 actually does what it's supposed to do and writes the correct data to scan1.dta.  If I comment this line out then no data appears.  Also I now get a Command Prompt window opened. It takes approx. eight seconds for ProcessWait() to terminate.

Edit: Tried "ShellExecute("data1.bat")" .. got a Command Prompt window for about eight seconds which closed without error but still no data saved. The batch file works perfectly from Command Prompt.

So there seems to be a bug in AutoIt when running some Command Line programs?

 

Edited by fopetesl

The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites
Jos
6 hours ago, fopetesl said:

It's clear that the 2nd Run() $DOS2 actually does what it's supposed to do and writes the correct data to scan1.dta.

Then use that format and don't tell AutoIt3 to capture the STDOUT & STDERR since you want to pipe that into a file anyways, or do you see any issues with that?

Jos


Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
fopetesl
16 hours ago, Jos said:

Then use that format and don't tell AutoIt3 to capture the STDOUT & STDERR since you want to pipe that into a file anyways, or do you see any issues with that?

Jos

I've no issue except the second (not $DOS2) call to capture data to scan2.dta always fails even if I call it twice

$DOS2 = Run(@ComSpec & " /k " & "data1.bat") ; 2nd call works here
Sleep(100)
$DOS3 = Run(@ComSpec & " /k " & "data2.bat")
Sleep(100)
$DOS3 = Run(@ComSpec & " /k " & "data2.bat") ; 2nd call here doesn't
Edited by fopetesl
Missing text

The most powerful number in the Universe.  Zero.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • TheSaint
      By TheSaint
      TeraCopy Timer - A program of mine, front end really, that I have been working on (on & off) for some time, but not shared here before, that I recall. Third party program TeraCopy is required.
      Many of you will be familiar with TeraCopy, and it has been discussed here at AF on several occasions, in various sub forums, including Chat.
      BE ADVISED - I still use an older version of TeraCopy (v2.27), a goody but an oldy, so have only tested my program with that. It may work with the newer v3.xx, or may be easily adjusted to do so, but I have not yet gone that route. Likewise, I only use it with Win 7 and Win XP, but I don't imagine there should be any issues with newer Windows. Add to that, my program being devised and created in AutoIt v3.3.0.0.
      So what is TeraCopy Timer and why might you need it?
      --------------------------------------------------------------------------------------
      Those familiar with TeraCopy use, know you can run multiple copy or move jobs either simultaneously or concurrently (one immediately after another has finished). With the free version at least, you have no control over precise order or timing, and no way to deal (without manual interaction) with the pesky Thumbs.db files in Win XP. TeraCopy Timer allows you to do all those things, and in a batch fashion.
      --------------------------------------------------------------------------------------
      Some screenshots and brief explanation
      Main Window
      Minimalist Window
      This new WAIT feature is the simplest and best way to use the program generally (in my view) ... but check out the following, as it is not always the case.
      Advanced Delay Window
      WARNING - It should go without saying, that you take all the usual precautions. For instance, don't use move with the only copy you have of precious files. BACKUP BACKUP BACKUP! Don't hold me liable for anything, except for being a nice guy who likes to share.
      TeraCopy Timer v2.8.zip  (see detail at Post #34)
      TeraCopy Timer v2.9.zip  (see detail at Post #35)
      Enjoy!
      OLDER DOWNLOADS
      P.S. I am not affiliated in any way with those who created and provide the excellent third party program - TeraCopy.
    • VollachR
      By VollachR
      I'm quite new to AutoIT and I have a very big batch file that I'm trying to completely re-write in Autoit, so far it's been going well but I got stuck with a certain part, hope someone can help.
      Here's the part of the batch script I'm currently stuck re-creating in AutoIT:
          :BeginLangMenu     if "%OptNum%" gtr "0" goto ShowLangMenu          ::Next Section code based on code supplied by Aacini from stackoverflow.com     :DefineLangMenu     for /L %%D in (1,1,99) do (        if exist Common\Settings\Data%%D.ini for /F "eol=# tokens=1,2 delims==" %%a in (Common\Settings\Data%%D.ini) do (                set line=%%a           if "!line:~2,5!" neq "clude" (              REM Define "normal" variables, i.e. Compressor, Method, etc.              set %%a=           ) else if "!line:~7!" neq "" (                   REM Define the base array elements, i.e. D1IncludeAR=%%b, D1ExcludeAR=%%b, ...              set D%%D%%a=%%b                   REM Set Show?? array elements with value equal 1, i.e. ShowAR=1, ...              REM when anyone of DiInclude?? or DiExclude?? corresponding elements was given              if defined D%%D%%a set Show!line:~7!=1                )        )     )          REM Define a list of language abbreviations, i.e. "langs=AR CZ DE ..."     REM and the corresponding language names array, i.e. lang[AR]=Arabic, ...     REM At same time, calculate original OptNum          for %%a in ("AR=Arabic" "CZ=Czech" "DE=German" "EN=English" "ES=Spanish" "ESMX=Spanish(Mexico)"                 "FR=French" "HU=Hungarian" "IT=Italian" "JP=Japanese" "KR=Korean" "PL=Polish"                 "PR=Portuguese" "PRBR=Portuguese(Brazil)" "RU=Russian" "ZH=Chinese") do (        for /F "tokens=1,2 delims==" %%b in (%%a) do (           set "langs=!langs! %%b"           set "lang[%%b]=%%c"           set /A "OptNum+=Show%%b"             )     )          ::NEXT 2 SECTIONS DISPLAYS THE LANGUAGE SELECTION MENU IF APPLICABLE     :ShowLangMenu     set /a step=%step%+1     :LangMenu     if "%OptNum%"=="0" Goto checksplit     echo %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2% - Showing Language Selection Menu >> "%workdir%Conversion.log"     REM Show the language menu     set #=0     for %%a in (%langs%) do (        if defined Show%%a (           set /A #+=1     rem       echo [!#!] !lang[%%a]!           echo !lang[%%a]! >> %b2eincfilepath%\Lang.txt           set "option[!#!]=%%a"         )     )               %MYFILES1%\DROPDOWNBOX.exe /F:"%b2eincfilepath%\Lang.txt" "Choose Which Language to Compress" "STEP %step%: Language Selection"  /W:280 /RI /C:13 >nul > %b2eincfilepath%\LangAnswer.txt     if %ERRORLEVEL% EQU 0 del %b2eincfilepath%\LangAnswer.txt     if exist %b2eincfilepath%\LangAnswer.txt set /p "SelectLang="<%b2eincfilepath%\LangAnswer.txt     if not defined SelectLang goto LangError     if %SelectLang%==Arabic Set LangOpt=AR     if %SelectLang%==Czech set LangOpt=CZ     if %SelectLang%==German set LangOpt=DE     if %SelectLang%==English set LangOpt=EN     if %SelectLang%==Spanish set LangOpt=ES     if %SelectLang%==Spanish(Mexico) set LangOpt=ESMX     if %SelectLang%==French set LangOpt=FR     if %SelectLang%==Hungarian set LangOpt=HU     if %SelectLang%==Italian set LangOpt=IT     if %SelectLang%==Japanese set LangOpt=JP     if %SelectLang%==Korean set LangOpt=KR     if %SelectLang%==Polish set LangOpt=PL     if %SelectLang%==Portuguese set LangOpt=PR     if %SelectLang%==Portuguese(Brazil) set LangOpt=PRBR     if %SelectLang%==Russian set LangOpt=RU     if %SelectLang%==Chinese set LangOpt=ZH     if defined SelectLang Goto LangSet          ::SETS THE LANGUAGE SELECTION ACCORDING TO USER INPUT IN LANGUAGE MENU     :LangSet     set "LangIs=%LangOpt%"  
      Basically, here's what I need to do:
       Read from specific section of INI file but ONLY the Keys that have a Value. OR: A way to remove the keys without the values from the Array created by IniReadSection. A way to then take these stored values, and create a list of Languages based last 2-4 characters of the Key names. At this point, that said list is shown to user in DropDown box, after user make selection I need a way to move the Value of the Key related to the selected Language to a Variable, and ONLY the value for that specific Language. That's it basically, the rest is more or less Variable manipulation which isn't a problem.
      A little Example:
      My INI file have a Section like this:
      [LangInclude] IncludeAR=a IncludeCZ= IncludeDE=b IncludeEN= IncludeES=c IncludeESMX= IncludeFR= IncludeHU=d IncludeIT= IncludeJP= IncludeKR=e IncludePL= IncludePR= IncludePRBR= IncludeRU= IncludeZH= I need to get Only the keys that are set, in this case: IncludeAR, IncludeDE, IncludeES, IncludeHU & IncludeKR.
      I then need to convert these to a list of languages, in this example it will be (Arabic, German, Spanish, Hungarian, Korean).
      That list will be turned to DropDown selection, that I can do easily once I get the list correctly.
      After the user Selected, let us say for the example purpose Spanish, I need the Value of IncludeES to be moved into a Variable, like this: $Var=c
      I hope somebody can help me because I'm stuck after Importing the INI section with IniReadSection, everything I tried so far failed, the best I managed to do is Sort the array to have all the keys with values either at the first rows or last rows.
      I need some ideas.
      Help appreciated.
      Thanks
       
    • rootx
      By rootx
      Hi, I need to convert this batch, I follow microsoft specs here https://technet.microsoft.com/en-us/library/bb491005.aspx
      Ex:
      start /b 1.exe "path\2.exe"
      start /b mypgrcommand
      start /b /wait 3.exe "path\4_.exe"
      taskkill /F /IM 5.exe
      Somethings like this...
      RunWait( @COMSPEC & " /c start /b 1.exe 'path\2.exe' start /b mypgrcommand start /b /wait 3.exe 'path\4_.exe' taskkill /F /IM 5.exe", "", @SW_SHOW ) Thx
    • Eggsplorer
      By Eggsplorer
      Hi,
      Ich hab ein Script für Windows Updates, dass nach dem OOBE aufgerufen werden soll. Run/RunOnce ist daher nicht möglich.
      Stattdessen möchte ich das Script in den Autostart schreiben lasse. Wenn die OOBE beendet wird und der Administrator angemeldet wird, soll das Update-Script einmalig aufgerufen werden und sich anschl. selbst löschen.
      Lang rede, kurzer Sinn:
      Wie kann ich folgendes Script in den Autostart schreiben?
      RunWait(@ComSpec & " /c " & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\UA\Scripts\win-updates.ps1 -MaxUpdatesPerCycle 100 -RestartRequired 1", "") Ich würde ungern eine BAT oder EXE reinkopieren, da ich es unsauber finde. Die müsste ja auch zusätzlich irgendwo liegen.
      Danke
      Eggsplorer
    • ur
      By ur
      I am running the tomcat batch file through autoit   and need to wait until the below line I get in console output.

      But when I am trying to read the console output using the ProcessEx UDF, I am getting only the partial output.
      So, can you please suggest how to handle this.
×