I had to do the same (execute command line calls and get the result) and came up with a more general solution.
It also corrects strange errors if the quoted paths are used in real calls using the /S flag for cmd.exe .
{ Exec with output stored in result. } { ResultString will only be altered if True is returned. } function ExecWithResult(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer; var ResultString: String): Boolean; var TempFilename: String; Command: String; begin TempFilename := ExpandConstant('{tmp}\~execwithresult.txt'); { Exec via cmd and redirect output to file. Must use special string-behavior to work. } Command := Format('"%s" /S /C ""%s" %s > "%s""', [ ExpandConstant('{cmd}'), Filename, Params, TempFilename]); Result := Exec(ExpandConstant('{cmd}'), Command, WorkingDir, ShowCmd, Wait, ResultCode); if not Result then Exit; LoadStringFromFile(TempFilename, ResultString); { Cannot fail } DeleteFile(TempFilename); { Remove new-line at the end } if (Length(ResultString) >= 2) and (ResultString[Length(ResultString) - 1] = #13) and (ResultString[Length(ResultString)] = #10) then Delete(ResultString, Length(ResultString) - 1, 2); end;
Using:
Success := ExecWithResult('ipconfig', '/all', '', SW_HIDE, ewWaitUntilTerminated, ResultCode, ExecStdout) or (ResultCode <> 0);
The result can also be loaded into the TStringList object to get all the rows:
Lines := TStringList.Create; Lines.Text := ExecStdout; { ... some code ... } Lines.Free;
Tobias81 Dec 03 '15 at 15:40 2015-12-03 15:40
source share