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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Déclarations privées }
procedure RunPowerShellCommand(const Command: string; OutputLines: TStringList);
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.RunPowerShellCommand(const Command: string; OutputLines: TStringList);
var
SecurityAttr: TSecurityAttributes;
StartInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
PipeRead, PipeWrite: THandle;
Buffer: array[0..1023] of AnsiChar;
BytesRead: DWORD;
begin
ZeroMemory(@SecurityAttr, SizeOf(SecurityAttr));
SecurityAttr.nLength := SizeOf(SecurityAttr);
SecurityAttr.bInheritHandle := True;
if not CreatePipe(PipeRead, PipeWrite, @SecurityAttr, 0) then
raise Exception.Create('Impossible de créer les pipes.');
try
ZeroMemory(@StartInfo, SizeOf(StartInfo));
StartInfo.cb := SizeOf(StartInfo);
StartInfo.hStdOutput := PipeWrite;
StartInfo.hStdError := PipeWrite;
StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
StartInfo.wShowWindow := SW_HIDE;
ZeroMemory(@ProcessInfo, SizeOf(ProcessInfo));
if not CreateProcess(nil, PChar('powershell -Command "' + Command + '"'),
nil, nil, True, CREATE_NO_WINDOW, nil, nil, StartInfo, ProcessInfo) then
raise Exception.Create('Échec de la création du processus PowerShell.');
CloseHandle(PipeWrite);
OutputLines.Clear;
repeat
if ReadFile(PipeRead, Buffer, SizeOf(Buffer) - 1, BytesRead, nil) and (BytesRead > 0) then
begin
Buffer[BytesRead] := #0;
OutputLines.Text := OutputLines.Text + string(Buffer);
end;
until BytesRead = 0;
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
finally
CloseHandle(PipeRead);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Results: TStringList;
begin
Results := TStringList.Create;
try
RunPowerShellCommand(
'Get-WmiObject Win32_SerialPort | ForEach-Object { "$($_.DeviceID) - $($_.Caption)" }',
Results
);
if Results.Count > 0 then
Memo.Lines.Assign(Results) // Affiche les résultats dans le Memo
else
ShowMessage('Aucune donnée n''a été récupérée.');
finally
Results.Free;
end;
end;
end. |
Partager