Powershell Example: Environment Variables

Function GetEnvVar{
param(
[Parameter(Mandatory=$true)][String]$varname
)
$val = [System.Environment]::GetEnvironmentVariable("$varname", "Machine")
if (!$val){
Log "$varname env variable not found!"
return ""
}
Log "$varname env variable found: $val"
return $val
}

Function SetEnvVar{
param(
[Parameter(Mandatory=$false)][String]$envname,
[Parameter(Mandatory=$false)][String]$envval
)
$beforeval = GetEnvVar $envname
Log "Before change ${envname}: $beforeval"

[System.Environment]::SetEnvironmentVariable($envname,$envval,[System.EnvironmentVariableTarget]::Machine)

$afterval = GetEnvVar $envname
Log "After change ${envname}: $afterval"
}

Function UpdateEnvVar{
param(
[Parameter(Mandatory=$true)][String]$envname,
[Parameter(Mandatory=$true)][String]$newVal
)

$tmpenv = GetEnvVar $envname
if ($tmpenv -eq $newVal){
Log "$envname already set to $newval"
}else{
SetEnvVar $envname $newVal
}
}

Function UpdateCLASSPATH{
param(
[Parameter(Mandatory=$true)][String]$oldpath,
[Parameter(Mandatory=$true)][String]$newpath
)
$tmpcp = GetEnvVar $CLASSPATH
if ($tmpcp -like "*${oldpath}*"){
$newcp = $tmpcp.Replace($oldpath, $newpath)
SetEnvVar $CLASSPATH $newcp
}else{
Log "CLASSPATH already contains $newpath"
}
}

This entry was posted in PowerShell. Bookmark the permalink.