You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi中点击按钮打开管理员权限的PowerShell?

需求可行:在Delphi中点击按钮启动管理员权限的PowerShell

这个需求完全可以实现,通过Windows API的ShellExecuteEx函数并指定runas动词,就能触发UAC权限提升提示,启动拥有管理员权限的PowerShell。

核心实现代码

在Delphi窗体的按钮点击事件中,添加以下代码即可:

uses
  ShellAPI, Windows;

procedure TForm1.Button1Click(Sender: TObject);
var
  SEInfo: TShellExecuteInfo;
begin
  ZeroMemory(@SEInfo, SizeOf(SEInfo));
  SEInfo.cbSize := SizeOf(TShellExecuteInfo);
  SEInfo.fMask := SEE_MASK_NOCLOSEPROCESS;
  SEInfo.lpVerb := PChar('runas'); // 触发权限提升
  SEInfo.lpFile := PChar('powershell.exe'); // 目标程序
  SEInfo.nShow := SW_SHOWNORMAL; // 窗口显示方式

  if not ShellExecuteEx(@SEInfo) then
    ShowMessage('启动失败,错误码:' + IntToStr(GetLastError));
end;

额外说明

  • runas是实现权限提升的关键参数,系统会弹出UAC确认对话框,用户确认后PowerShell将以管理员身份运行。
  • 如果需要给PowerShell传递参数(比如执行指定脚本),可以在SEInfo.lpParameters字段中设置,示例:
    SEInfo.lpParameters := PChar('-File "C:\YourPath\YourScript.ps1"');
    

内容的提问来源于stack exchange,提问作者SzaBee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 17:12:06