In the previous tip we explained how you can set environment variables in all available scopes. But how would you remove environment variable?

Coincidentally, you can do that the same way, simply by providing an empty string as value. However, the function from our previous tip will not accept empty strings for the -VariableValue parameter:

function Set-EnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)][String]
        $VariableName,
        
        [Parameter(Mandatory)][String]
        $VariableValue,
        
        [Parameter(Mandatory)][EnvironmentVariableTarget]
        $Target        
    )
    
   [Environment]::SetEnvironmentVariable($VariableName, $VariableValue, $Target)
}

When you try it, this is what you will get:

 
PS C:\>  Set-EnvironmentVariable -VariableName test -VariableValue "" -Target  User
Set-EnvironmentVariable  : Cannot bind Argument to Parameter "VariableValue" because it is an  empty string.
...
 

This happens because whenever you declare a parameter as “Mandatory”, PowerShell refuses empty and null values by default.

You could make “VariableValue” optional but then PowerShell would no longer prompt for it when you run the function without arguments. How do you tell a mandatory parameter to accept null and empty string values?

By adding the attributes [AllowNull()] and/or [AllowEmptyString()]! With just a little effort, the function above can be turned into one that can also delete environment variables:

function Set-EnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)][String]
        $VariableName,
        
        [Parameter(Mandatory)][String]
        [AllowEmptyString()]
        $VariableValue,
        
        [Parameter(Mandatory)][EnvironmentVariableTarget]
        $Target        
    )
    
    [Environment]::SetEnvironmentVariable($VariableName, $VariableValue, $Target)
}

And here is the call to delete “Test” environment variable:

 
PS C:\> Set-EnvironmentVariable -VariableName test -VariableValue "" -Target User
 

Twitter This Tip! ReTweet this Tip!

Anonymous