Create an environmental variable

We can easily use New-Item to work with the environment provider

New-Item -Path env: -Name Myenv -Value "Hello"

but this only creates a variable that lasts the duration of the PowerShell session

 

To create a permanent environmental variable we need to drop down to .NET

[System.Environment]::SetEnvironmentVariable("MyPermEnvVar", "I am here for good", "User")

 

If you want a Machine level variable replace “User” with “Machine”.  if you use “Process” instead its the equivalent of using New-Item in our first example.

The new variable won’t be visible/usable until PowerShell is restarted.

What we need is a function that combines these two approaches.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016

function new-environment {
param
 (
 
[string][ValidateNotNullOrEmpty()]$name,
 [string][ValidateNotNullOrEmpty()]$value,
 [switch]$perm,
 [switch]$machine

)

 
if (-not $perm) {New-Item -Path env:\ -Name $($name) -Value $($value
)}
 
else
 {
 
if ($machine){$type = "Machine"
}
 
else {$type = "User"
}
 
[System.Environment]::SetEnvironmentVariable($name, $value, $type)
 }
}

Leave a Reply