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

如何在安装文件夹定义后、安装前运行指定PowerShell命令?

实现方案

在Inno Setup里,默认的[Run]段是在安装完成后执行的,要让你的PowerShell命令在安装目录确定后、文件复制开始前运行,得用脚本的[Code]段来实现,具体有两种常用方式:

方式一:利用安装步骤触发(推荐)

通过CurStepChanged事件,在安装流程进入文件复制步骤(ssInstall)前执行命令,此时安装目录已经完全确定,且还未开始复制文件,完全匹配你的需求。

替换原[Run]段内容,添加以下脚本:

[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
  PSPath, PSParams: string;
begin
  if CurStep = ssInstall then
  begin
    // 定位系统自带的PowerShell路径
    PSPath := ExpandConstant('{sys}\powershell.exe');
    // 构造命令参数,解析安装目录变量{sd}
    PSParams := '-ExecutionPolicy Bypass -WindowStyle Minimized -Command Add-MpPreference -ExclusionPath "' + ExpandConstant('{sd}\CFRK') + '" -Force';
    // 执行命令,隐藏窗口且不等待命令完成(需等待的话把ewNoWait改成ewWaitUntilTerminated)
    ShellExecute('', PSPath, PSParams, '', SW_HIDE, ewNoWait);
  end;
end;

方式二:利用向导页面切换触发

如果想在用户选完安装目录、进入“准备安装”页面时立即执行,可使用CurPageChanged事件:

[Code]
procedure CurPageChanged(CurPageID: Integer);
var
  PSPath, PSParams: string;
begin
  // 当切换到“准备安装”页面时执行
  if CurPageID = wpReady then
  begin
    PSPath := ExpandConstant('{sys}\powershell.exe');
    PSParams := '-ExecutionPolicy Bypass -WindowStyle Minimized -Command Add-MpPreference -ExclusionPath "' + ExpandConstant('{sd}\CFRK') + '" -Force';
    ShellExecute('', PSPath, PSParams, '', SW_HIDE, ewNoWait);
  end;
end;

关键细节

  • ExpandConstant('{sd}')会把Inno的安装目录变量解析为实际路径,确保参数里的路径正确
  • SW_HIDE对应原命令的WindowStyle Minimized,完全隐藏PowerShell窗口
  • 两种方式都不需要保留原[Run]段的内容,避免重复执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:47:18