Reputation: 2945
I am writing a powershell-v2.0 script. The script contains a function to set environment variable. The function is as follows:
function SetSvnEnvironmentVariable($path)
{
# Get the Path environment variable
$pathVar = [Environment]::GetEnvironmentVariable("Path","User")
# Check if path environment variable already contains the path to be added
if(-Not ($pathVar -like $path))
{
$pathVar += $path
[Environment]::SetEnvironmentVariable("Path",$pathVar, [System.EnvironmentVariableTarget]::User)
}
}
The $path
variable contains the path to be added to the PATH environment variable.
The problem I am facing is, even though $path
is a substring of $pathVar
, the if condition always returns False
.
Following are the values of $pathVar
and $path
.
$pathVar
:
C:\Program Files (x86)\MATLAB\R2009b\bin\win32;C:\Program Files\TortoiseSVN\bin
$path
:
;C:\Program Files\TortoiseSVN\bin
Upvotes: 0
Views: 294
Reputation: 200203
Using wildcard or regular expression matches for this kind of check bears the risk of getting false positives if the path already contains a subfolder of the folder you want to add. It's better to split the value of the environment variable at semicolons and use the -contains
/-notcontains
operator to check if the resulting array does or doesn't contain the item you want to add:
function SetSvnEnvironmentVariable($path)
{
$pathVar = [Environment]::GetEnvironmentVariable('Path', 'User')
if ($pathVar.Split(';') -notcontains $path))
{
$pathVar += ";$path"
[Environment]::SetEnvironmentVariable('Path', $pathVar, [EnvironmentVariableTarget]::User)
}
}
Note that $path
should not be specified with a leading (or trailing) semicolon.
Upvotes: 1
Reputation: 2945
Using a wildcard fixed my problem. -like
operator without a wildcard compared the strings if they were equal and hence always returned False
.
By changing the if
condition as follows, the if
condition returns True
:
if(-Not ($pathVar -like "*$path*"))
{
....
}
Upvotes: 0