When we last left this series, I showed you how to create and modify environment variables using PowerShell in our 2nd installment. And, just before that, I kicked-off the series with the basics of how to retrieve the list of local environment variables. In this final installment in the Environment Variables series, I'll show you how to delete environment variables.
There's a couple ways to accomplish deleting environment variables. Of course, if it was a variable you created using the method outlined in the 2nd part of the series, you know exactly what to delete. However, this is another instance where knowing how to list out the existing variables is critically important to ensure you delete the correct environment variable, or to guarantee that your deletion method is actually doing something.
The first way to delete an environment variable is so use the Remove-Item Env: method. The following PowerShell one-liner shows how to do this using the MyTestVariable example used in the previous pieces to this series:
Remove-Item is a quick and easy way to remove the environment variable from the system. But, if you're hankering to know everything about deleting environment variables, and you were pretty excited about what the .NET SystemEnvironmentVariable gives you (again, shown in the 2nd installment of the series) there's also a .NET way to do it.
Remember, with the .NET Framework component, you have access to the varying levels of environment variables (User, Machine, and Process) so you'll want to take this into account when working with it. The following PowerShell one-liner invokes the .NET component and sets the environment variable (again, the MyTestVariable) to null, while also ensuring that the User-level environment variable is removed.
That's it! Working with environment variables in PowerShell seems simple, but it's one of those often overlooked yet extremely critical pieces of scripting.
Again, in case you missed the previous installments in this series, you'll definitely want to go back and review them, particularly if you read about the environment levels above and are left scratching your head about what my references there actually mean.
Here's the links to the previous articles: