[Environment]::GetEnvironmentVariables()
You can also use the below .NET function to return the value of particular environment variable:
[Environment]::GetEnvironmentVariable("Temp","User")
Temp – The name of the environment variable we want to retrieve;
User – The type of environment variable. The User type is an environment variable tied to a user profile. You can also retrieve Machine environment variables
by passing the parameter “Machine“.
Create/Set Environment Variable
We can create two kinds of variables, process-level environment variable (temporary) and permanent environment variable.
Process-level Environment variable (temporary):
The process-level environment variable is a temporary variable, its value lasts only as long as your current powershell session alive. Use the below command to
create a temporary environment variable.
$Env:TestVariable = "This is a temporary environment variable."
Permanent Environment variable:
To create a permanent environment variable you need to use the .NET method SetEnvironmentVariable . The below command creates a user-level environment variable named TestVariable:
[Environment]::SetEnvironmentVariable("TestVariable", "This is a permanent variable.", "User")
If TestVariable does not exist. powershell will create the new environment variable. If TestVariable already exist, then powershell will update the value “This is a permanent variable.” in TestVariable.
Delete/Remove Environment Variables
We can remove Environment variable if it no longer needed, by using Remove-Item cmdlet.
Remove-Item Env:TestVariable
You can also remove Environment variable by assigning the variable value as null using SetEnvironmentVariable method:
[Environment]::SetEnvironmentVariable("TestVariable",$null,"User")
But, if you use SetEnvironmentVariable method to remove, the deleted variable might still show up when you call Get-ChildItem, at least until you restart powershell. But the environment variable will no longer exist when you call GetEnvironmentVariables.
[Environment]::GetEnvironmentVariable("TestVariable","User")