Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Command Line not working 3

Status
Not open for further replies.

kr0me

Programmer
Feb 12, 2007
2
GB
Hi,

I am trying to execute a command using delphi, as if I had typed it into the windows command prompt.

I am using this code to do it:

Code:
function OpenCmdLine(const CmdLine: string;
  WindowState: Word): Boolean;
var
  SUInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
begin
  { Enclose filename in quotes to take care of
    long filenames with spaces. }
  FillChar(SUInfo, SizeOf(SUInfo), #0);
  with SUInfo do
  begin
    cb := SizeOf(SUInfo);
    dwFlags := STARTF_USESHOWWINDOW;
    wShowWindow := WindowState;
  end;
  Result := CreateProcess(nil, PChar(CmdLine), nil, nil, False,
    CREATE_NEW_CONSOLE or
    NORMAL_PRIORITY_CLASS, nil,
    nil {PChar(ExtractFilePath(Filename))},
    SUInfo, ProcInfo);
end;

This definatley works with at least some commands, for example the net send command.

However, I am trying to use it to create a text file with a directory listing.

If you open up a command prompt and type "dir C:\ > C:\hello.txt" then it dumps the output of the command to C:\hello.txt.
Try it yourself, it works.

But, when I try it in delphi, it doesnt work :(

Can anyone suggest why it wouldnt work, how to fix it, or any alternatives?

Thanks,
kr0me
 
Commands such as DIR are built into the Command Interpreter (CMD.EXE), so you need to pass your command line to that, whereas commands such as NET are external. Use something like: [tt]'CMD.EXE /C ' + CmdLine[/tt] (not tested, but should work). The /C tells CMD to Close after it has finished.


Hope this helps.

[vampire][bat]
 
Thanks for your help,

I ended up writing the commands to a batch file and then running it, it solved the problem for what I needed to do.

Thankyou for your responses, I am sure they will help me in future projects!

kr0me
 
Try this:
Code:
  if not FileExists(OutFile) then begin
    rc:= ShellExecute(0, 'open', pchar('cmd.exe'), pchar('/C ipconfig.exe /all >' + OutFile), NIL, SW_SHOWNORMAL);
This example will pipe the output from ipconfig.exe to file name assigned to OutFile. I use:

const
OutFile = 'ipconfig.txt';


Roo
Delphi Rules!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top