Run PowerShell Command as Administrator in Delphi

CK CK 3788 
Created at
Updated at  
658 0 0

To capture the output of the PowerShell command and store it in a string variable, you can modify the RunPowerShellCommandAsAdmin procedure to redirect the output of the PowerShell process and read it into a string. 

uses
  Classes, Process, ShellAPI, SysUtils;

function RunPowerShellCommandAsAdmin(const ACommand: string): string;
var
  ShellExecuteInfo: TShellExecuteInfo;
  Output: TStringStream;
  ProcessHandle: THandle;
  BytesRead: DWORD;
  Buffer: array[0..1023] of AnsiChar;
begin
  Output := TStringStream.Create('');
  try
    FillChar(ShellExecuteInfo, SizeOf(ShellExecuteInfo), 0);
    ShellExecuteInfo.cbSize := SizeOf(ShellExecuteInfo);
    ShellExecuteInfo.lpVerb := 'runas'; // Requesting elevation
    ShellExecuteInfo.lpFile := 'powershell.exe';
    ShellExecuteInfo.lpParameters := PChar('-NoProfile -ExecutionPolicy Bypass -Command "' + ACommand + '"');
    ShellExecuteInfo.nShow := SW_HIDE; // Hide the PowerShell window
    ShellExecuteInfo.fMask := SEE_MASK_NOCLOSEPROCESS;

    if not ShellExecuteEx(@ShellExecuteInfo) then
      raise Exception.Create('Failed to execute PowerShell command as admin');

    ProcessHandle := ShellExecuteInfo.hProcess;
    repeat
      if not ReadFile(ShellExecuteInfo.hProcess, Buffer, Length(Buffer), BytesRead, nil) then
        Break;
      Output.Write(Buffer, BytesRead);
    until BytesRead = 0;

    // Wait for the process to exit
    WaitForSingleObject(ProcessHandle, INFINITE);

    Result := Output.DataString;
  finally
    Output.Free;
    CloseHandle(ProcessHandle);
  end;
end;

// Usage
procedure TForm1.RunButtonClick(Sender: TObject);
var
  Output: string;
begin
  Output := RunPowerShellCommandAsAdmin('Your-PowerShell-Command-Here');
  Memo1.Text := Output;
end;

In this modified code:

  • We create a TStringStream object named Output to store the output of the PowerShell command.
  • After executing the PowerShell command with elevated privileges, we read the output of the process using the ReadFile function.
  • The output is continuously read into the Output string stream until the end of the output is reached.
  • We wait for the PowerShell process to exit using the WaitForSingleObject function to ensure that we capture the complete output.
  • Finally, we return the content of the Output string stream as a string, which contains the output of the PowerShell command.

Now, when you call RunPowerShellCommandAsAdmin, it will execute the PowerShell command with elevated privileges and return the output as a string. You can then assign this output to your TMemo component or use it as needed in your Delphi application.

Tags Administrator PowerShell RunPowerShellCommandAsAdmin ShellAPI ShellExecute Facebook X
Comments 0
Similar posts
  1. Run command with Administrator permission in Delphi on Microsoft Windows
    767
  2. Delphi Program can command level execution program with hidden mode
    703
  3. How to launch the external application in Delphi ?
    1,074
  4. How to print external document ?
    423
  5. How to install an INF file using Delphi ?
    469
  6. Copying Group of Files using Delphi with Standard Animation Dialog (SHFileOperation)
    415
  7. How to run shell command by MFC ?
    441
  8. How To Open Url In Default Webbrowser
    465
  1. Building a Simple DNS Server in Delphi with TTL Support
    686
  2. Delphi code to send data to web server based on POST method
    1,036
  3. Good Delphi components
    930
  4. How to download/grap web pages or XML document at internet website in Delphi XE?
    880
  5. How To Turn On/Off Monitor with Delphi
    857
  6. How to get application version number in Delphi
    1,559
  7. The Delphi function to get My Videos folder
    2,337
  8. Get Application Data Path on Delphi
    839
  9. I want to select directory(folder) not file. How can I do that ?
    624
  10. Changing the Title of a Print Dialog in Delphi
    1,098
  11. Auto Logon Programming in Delphi
    1,034
  12. Thread Application Implementation in TThread
    670
  13. Is there directory selection VCL component in Delphi ?
    523
  14. Delphi API to get windows temporary directory
    586
  15. Delphi API to get the current working directory
    1,254
  16. How to resize PNG file in Delphi ?
    1,224
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,884
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232