I have posted before on the nuances of handling environment variables with PowerShell. I recently encountered an issue where I found a shortcoming of some of my previous scripting work. I was unable to clear nullified environment variables in my current session. I can’t take credit for the script I pieced together to accomplish this, because it was constructed from multiple answers on Stack Exchange.
This script will clear environment variables that you have nullified.
# Clear nullified environment variables
# Get all environment variables for the current Process, as well as System and User environment variable values
$machineValues = [Environment]::GetEnvironmentVariables('Machine')
$userValues = [Environment]::GetEnvironmentVariables('User')
# Identify the entire list of environment variable names first
$envVarNames = ($machineValues.Keys + $userValues.Keys + 'PSModulePath') | Sort-Object | Select-Object -Unique
# Lastly remove the environment variables that no longer exist
foreach ($envVarName in $processValues.Keys | Where-Object {$envVarNames -like $null}) {
Remove-Item -LiteralPath "env:${envVarName}"
}