?
Solved

Running DOS command and Capture The Results

Posted on 2003-03-25
6
Medium Priority
?
1,168 Views
Last Modified: 2007-12-19
I need to run DOS commands (such as DIR, MKDIR, FORMAT, etc)
and capture the produced output. I have tried a few
options to execute external programs from Delphi (WinExec and FileRun)
but those functions do not capture the output (or do they?).
Does anyone know any other way to do this trick?

greeting,
f-hu
0
Comment
Question by:Fresh_
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 27

Expert Comment

by:kretzschmar
ID: 8201247
use like

dir > result.txt

and open then the file result.txt

meikl ;-)
0
 

Expert Comment

by:zodiac7
ID: 8201922
I think you need to use the win32 api call CreateProcess here, substituting the output streams with your own..
you could also use ShellExecuteEx but I found CreateProcess
to be better, also for dos commands, you need to execute them with the shell (command.exe/cmd.exe)

links to code -

http://homepages.borland.com/torry/samples/samples/soft/console.zip
http://homepages.borland.com/torry/samples/samples/soft/redirectconsole.zip
0
 
LVL 14

Accepted Solution

by:
DragonSlayer earned 80 total points
ID: 8208921
{
 Example call   : CreateDOSProcessRedirected('C:\MyDOSApp.exe',
                                             'C:\InputPut.txt',
                                             'C:\OutPut.txt',
                                             'Please, record this message')
-----------------------------------------------------------------------------------}
function CreateDOSProcessRedirected(const CommandLine, InputFile, OutputFile, ErrMsg :string):boolean;
const
  ROUTINE_ID = '[function: CreateDOSProcessRedirected ]';
var
  OldCursor     : TCursor;
  pCommandLine  : array[0..MAX_PATH] of char;
  pInputFile,
  pOutPutFile   : array[0..MAX_PATH] of char;
  StartupInfo   : TStartupInfo;
  ProcessInfo   : TProcessInformation;
  SecAtrrs      : TSecurityAttributes;
  hAppProcess,
  hAppThread,
  hInputFile,
  hOutputFile   : THandle;
begin

  Result := False;

  { check for InputFile existence }
  if not FileExists(InputFile)
  then
    raise Exception.CreateFmt(ROUTINE_ID          + #10 +  #10 +
                              'Input file * %s *' + #10 +
                              'does not exist'    + #10 +  #10 +
                              ErrMsg, [InputFile]);

  { save the cursor }
  OldCursor     := Screen.Cursor;
  Screen.Cursor := crHourglass;

  { copy the parameter Pascal strings to null terminated strings }
  StrPCopy(pCommandLine, CommandLine);
  StrPCopy(pInputFile, InputFile);
  StrPCopy(pOutPutFile, OutputFile);

  TRY

    { prepare SecAtrrs structure for the CreateFile calls
      This SecAttrs structure is needed in this case because
      we want the returned handle can be inherited by child process
      This is true when running under WinNT.
      As for Win95 the documentation is quite ambiguous }
    FillChar(SecAtrrs, SizeOf(SecAtrrs), #0);
    SecAtrrs.nLength              := SizeOf(SecAtrrs);
    SecAtrrs.lpSecurityDescriptor := nil;
    SecAtrrs.bInheritHandle       := True;

    { create the appropriate handle for the input file }
    hInputFile := CreateFile(
                             pInputFile,                            { pointer to name of the file }
                             GENERIC_READ or GENERIC_WRITE,         { access (read-write) mode }
                             FILE_SHARE_READ or FILE_SHARE_WRITE,   { share mode }
                             @SecAtrrs,                             { pointer to security attributes }
                             OPEN_ALWAYS,                           { how to create }
                             FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
                             0 );                                   { handle to file with attributes to copy }


    { is hInputFile a valid handle? }
    if hInputFile = INVALID_HANDLE_VALUE
    then
      raise Exception.CreateFmt(ROUTINE_ID                                                     + #10 +  #10 +
                                'WinApi function CreateFile returned an invalid handle value'  + #10 +
                                'for the input file * %s *'                                    + #10 + #10 +
                                ErrMsg, [InputFile]);

    { create the appropriate handle for the output file }
    hOutputFile := CreateFile(
                              pOutPutFile,                           { pointer to name of the file }
                              GENERIC_READ or GENERIC_WRITE,         { access (read-write) mode }
                              FILE_SHARE_READ or FILE_SHARE_WRITE,   { share mode }
                              @SecAtrrs,                             { pointer to security attributes }
                              CREATE_ALWAYS,                         { how to create }
                              FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
                              0 );                                   { handle to file with attributes to copy }

    { is hOutputFile a valid handle? }
    if hOutputFile = INVALID_HANDLE_VALUE
    then
      raise Exception.CreateFmt(ROUTINE_ID                                                     + #10 +  #10 +
                                'WinApi function CreateFile returned an invalid handle value'  + #10 +
                                'for the output file * %s *'                                   + #10 + #10 +
                                ErrMsg, [OutputFile]);

    { prepare StartupInfo structure }
    FillChar(StartupInfo, SizeOf(StartupInfo), #0);
    StartupInfo.cb          := SizeOf(StartupInfo);
    StartupInfo.dwFlags     := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
    StartupInfo.wShowWindow := SW_HIDE;
    StartupInfo.hStdOutput  := hOutputFile;
    StartupInfo.hStdInput   := hInputFile;

    { create the app }
    Result := CreateProcess(nil,                           { pointer to name of executable module }
                            pCommandLine,                  { pointer to command line string }
                            nil,                           { pointer to process security attributes }
                            nil,                           { pointer to thread security attributes }
                            True,                          { handle inheritance flag }
                            CREATE_NEW_CONSOLE or
                            REALTIME_PRIORITY_CLASS,       { creation flags }
                            nil,                           { pointer to new environment block }
                            nil,                           { pointer to current directory name }
                            StartupInfo,                   { pointer to STARTUPINFO }
                            ProcessInfo);                  { pointer to PROCESS_INF }

    { wait for the app to finish its job and take the handles to free them later }
    if Result
    then
      begin
        WaitforSingleObject(ProcessInfo.hProcess, INFINITE);
        hAppProcess  := ProcessInfo.hProcess;
        hAppThread   := ProcessInfo.hThread;
      end
    else
      raise Exception.Create(ROUTINE_ID          + #10 +  #10 +
                             'Function failure'  + #10 +  #10 +
                             ErrMsg);

  FINALLY
    { close the handles
      Kernel objects, like the process and the files we created in this case,
      are maintained by a usage count.
      So, for cleaning up purposes we have to close the handles
      to inform the system that we don't need the objects anymore }
    if hOutputFile <> 0 then CloseHandle(hOutputFile);
    if hInputFile <> 0 then CloseHandle(hInputFile);
    if hAppThread <> 0 then CloseHandle(hAppThread);
    if hAppProcess <> 0 then CloseHandle(hAppProcess);
    { restore the old cursor }
    Screen.Cursor:= OldCursor;
  END;

end;
0
 

Expert Comment

by:CleanupPing
ID: 9316618
Fresh_:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses
Course of the Month8 days, 3 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question