1 // Returns the
value(s
) of the environment variable
"VarName", which
is tokenized
2 // by
";" into an
array of strings
. This makes it easy query PATH
-like variables
3 // in addition
to normal variables
. If "AllUsers" is true, the common variables
4 // are searched
, else the user
-specific ones
.
5 function GetEnvStrings(VarName
:string;AllUsers
:Boolean):TArrayOfString
;
13 // See http
://www
.jrsoftware
.org
/isfaq
.php#env
14 if AllUsers
then begin
15 // We ignore errors here
. The resulting
array of strings will be empty
.
16 RegQueryStringValue(HKEY_LOCAL_MACHINE
,'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',VarName
,Path
);
18 // We ignore errors here
. The resulting
array of strings will be empty
.
19 RegQueryStringValue(HKEY_CURRENT_USER
,'Environment',VarName
,Path
);
22 // Fallback
for built
-in variables which are
not stored
in the Registry
.
23 if Length(Path
)=0 then begin
24 Path
:=ExpandConstant('{%'+VarName
+'}');
27 // Make sure we have at least one semicolon
.
30 // Split the directories
in PATH into an
array of strings
.
32 SetArrayLength(Result
,0);
36 SetArrayLength(Result
,i
+1);
38 Result
[i
]:=Copy(Path
,1,p
-1);
41 Path
:=Copy(Path
,p
+1,Length(Path
));
46 // Sets the contents
of the specified environment variable
for the current process
.
47 function SetEnvironmentVariable(lpName
,lpValue
:String):Boolean;
49 external 'SetEnvironmentVariableW@Kernel32.dll stdcall delayload';
51 external 'SetEnvironmentVariableA@Kernel32.dll stdcall delayload';
54 // Sets the environment variable
"VarName" to the concatenation
of "DirStrings"
55 // using
";" as the delimiter
. If "AllUsers" is true, a common variable
is set,
56 // else a user
-specific one
. If "DeleteIfEmpty" is true and "DirStrings" is
57 // empty
, "VarName" is deleted instead
of set if it exists
.
58 function SetEnvStrings(VarName
:string;AllUsers
,DeleteIfEmpty
:Boolean;DirStrings
:TArrayOfString
):Boolean;
63 // Merge all non
-empty directory strings into a PATH variable
.
65 for i
:=0 to GetArrayLength(DirStrings
)-1 do begin
66 if Length(DirStrings
[i
])>0 then begin
67 if Length(Path
)>0 then begin
68 Path
:=Path
+';'+DirStrings
[i
];
75 // See http
://www
.jrsoftware
.org
/isfaq
.php#env
76 if AllUsers
then begin
77 KeyName
:='SYSTEM\CurrentControlSet\Control\Session Manager\Environment';
78 if DeleteIfEmpty
and (Length(Path
)=0) then begin
79 Result
:=(not RegValueExists(HKEY_LOCAL_MACHINE
,KeyName
,VarName
)) or
80 RegDeleteValue(HKEY_LOCAL_MACHINE
,KeyName
,VarName
);
82 Result
:=RegWriteStringValue(HKEY_LOCAL_MACHINE
,KeyName
,VarName
,Path
);
85 KeyName
:='Environment';
86 if DeleteIfEmpty
and (Length(Path
)=0) then begin
87 Result
:=(not RegValueExists(HKEY_CURRENT_USER
,KeyName
,VarName
)) or
88 RegDeleteValue(HKEY_CURRENT_USER
,KeyName
,VarName
);
90 Result
:=RegWriteStringValue(HKEY_CURRENT_USER
,KeyName
,VarName
,Path
);
94 // Also update the environment
of the current process
.
95 SetEnvironmentVariable(VarName
,Path
);