Win10下Inno Setup添加环境变量脚本

 

用 Inno Setup Script Wizard 创建脚本后,在[Setup]增添如下项(此项可保证添加环境变量立即生效,无需重启电脑):

ChangesEnvironment=yes

 

在 [Files] 和 [Icons] 之间插入以下代码:

[Registry]
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; \
    ValueType: expandsz; ValueName: "PATH"; ValueData: "{olddata};{app}\bin"; \
    Check: NeedsAddPath(ExpandConstant('{app}\bin'))
    
[Code]
const
  EnvironmentKey = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';
  
function NeedsAddPath(Param: string): boolean;
var
  OrigPath: string;
begin
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE, EnvironmentKey, 'Path', OrigPath) then
  begin
    Result := True;
    exit;
  end;
  // look for the path with leading and trailing semicolon
  // Pos() returns 0 if not found
  Result := Pos(';' + Param + ';', ';' + OrigPath + ';') = 0;
end;

procedure RemovePath(Path: string);
var
  Paths: string;
  P: Integer;
begin
  if not RegQueryStringValue(HKEY_LOCAL_MACHINE, EnvironmentKey, 'Path', Paths) then
  begin
    Log('PATH not found');
  end
    else
  begin
    Log(Format('PATH is [%s]', [Paths]));
    P := Pos(';' + Uppercase(Path) + ';', ';' + Uppercase(Paths) + ';');
    if P = 0 then
    begin
      Log(Format('Path [%s] not found in PATH', [Path]));
    end
      else
    begin
      if P > 1 then P := P - 1;
      Delete(Paths, P, Length(Path) + 1);
      Log(Format('Path [%s] removed from PATH => [%s]', [Path, Paths]));
      if RegWriteStringValue(HKEY_LOCAL_MACHINE, EnvironmentKey, 'Path', Paths) then
      begin
        Log('PATH written');
      end
        else
      begin
        Log('Error writing PATH');
      end;
    end;
  end;
end;

procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
  if CurUninstallStep = usUninstall then
  begin
    RemovePath(ExpandConstant('{app}\bin'));
  end;
end;

 

注:若要正确解析类似 {app} 和 {username} 的超文本,需将含有这类变量的字符串外套上 ExpandConstant 函数,例如:

NeedsAddPath(ExpandConstant('{app}\bin'))

 

一般环境变量都是在安装目录下的 bin 目录中,对于不在 bin 目录的特殊场景需要手动修改;本脚本支持安装时自动添加环境变量、卸载时自动清除环境变量而不影响其它环境变量、覆盖安装时不重复添加环境变量。

posted @ 2022-08-19 18:54  天才俱乐部  阅读(729)  评论(0)    收藏  举报