Home » How to Remove Environment Variable in PowerShell

How to Remove Environment Variable in PowerShell

PowerShell provides multiple ways to remove an environment variable.

Method 1: Using the Remove-Item cmdlet with the Env: Drive

Remove-Item -Path Env:\my_variable

This script removes an environment variable my_variable from the current PowerShell session, as well as from the system environment variables.

Method 2: Using the [Environment] class to Remove Environment Variable

[Environment]::SetEnvironmentVariable("my_variable", $null, "Machine")

This script removes the environment variable my_variable permanently from the system environment variable.

Both these methods are used to delete environment variables in PowerShell.

The following example shows how to remove the environment variable.

Using the Remove-Item cmdlet to Remove Environment Variable

The Remove-Item cmdlet on the env: drive provider in PowerShell removes the environment variable from the current PowerShell session.

This example shows how to use it with syntax.

Remove-Item -Path Env:\RConstant

In this example, it deletes the RConstant environment variable.

If you try to get the environment variable using the following script, it will throw an exception as “it does not exist“.

Get-ChildItem -Path Env:\RConstant

Output:

(base) PS C:\> Get-ChildItem -Path Env:\RConstant
Get-ChildItem : Cannot find path 'RConstant' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path Env:\RConstant
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (RConstant:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

(base) PS C:\>

Using the [Environment] class to Remove Environment Variable

You can use the static method [SetEnvironmentVariable] of the [Environment] class to set an environment variable with a value of $null.

The following PowerShell script shows how to use it.

[Environment]::SetEnvironmentVariable("RConstant", $null, "Machine")

In this example, the “RConstant” environment variable will be removed from the machine-level environment variable by setting its value to $null.

Conclusion

I hope the above article on how to remove an environment variable in PowerShell using the Remove-Item and [Environment] class methods is useful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.