1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69:
| function ExecConsoleCommand(const ACommand: String; var AOutput, AErrors: String; var AExitCode: Cardinal): Boolean; var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; SecurityAttr: TSecurityAttributes; PipeOutputRead, PipeOutputWrite, PipeErrorsRead, PipeErrorsWrite: THandle;
procedure ReadPipeToString(const hPipe: THandle; var Result: String); var AvailableBytes, ReadBytes: Cardinal; Buffer: String; begin PeekNamedPipe(hPipe, NIL, 0, NIL, @AvailableBytes, NIL); while (AvailableBytes > 0) do begin SetLength(Buffer,AvailableBytes); if ReadFile(hPipe,PChar(Buffer)^,AvailableBytes,ReadBytes,NIL) then if (ReadBytes > 0) then begin SetLength(Buffer,ReadBytes); Result := Result +Buffer; end; PeekNamedPipe(hPipe, NIL, 0, NIL, @AvailableBytes, NIL); end; end;
begin AOutput := ''; AErrors := ''; FillChar(ProcessInfo,SizeOf(TProcessInformation),0); FillChar(SecurityAttr,SizeOf(TSecurityAttributes),0); SecurityAttr.nLength := SizeOf(SecurityAttr); SecurityAttr.bInheritHandle := TRUE; SecurityAttr.lpSecurityDescriptor := NIL; CreatePipe(PipeOutputRead,PipeOutputWrite,@SecurityAttr,0); CreatePipe(PipeErrorsRead,PipeErrorsWrite,@SecurityAttr,0); FillChar(StartupInfo,SizeOf(TStartupInfo),0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.hStdInput := 0; StartupInfo.hStdOutput := PipeOutputWrite; StartupInfo.hStdError := PipeErrorsWrite; StartupInfo.wShowWindow := SW_HIDE; StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; Result := CreateProcess(NIL,PChar(ACommand),NIL,NIL,TRUE, CREATE_DEFAULT_ERROR_MODE or CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, NIL,NIL,StartupInfo,ProcessInfo); if Result then begin repeat GetExitCodeProcess(ProcessInfo.hProcess,AExitCode); ReadPipeToString(PipeOutputRead,AOutput); ReadPipeToString(PipeErrorsRead,AErrors); if (AExitCode = STILL_ACTIVE) then Sleep(1); until (AExitCode <> STILL_ACTIVE); CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); end; CloseHandle(PipeOutputWrite); CloseHandle(PipeErrorsWrite); CloseHandle(PipeOutputRead); CloseHandle(PipeErrorsRead); end; |