Function: Remove-ScriptVariables – Cleaning Up Script Variables in PowerShell
Description
When writing scripts that use variables, especially those that contain a fair amount of data, it’s best practice to clean up the environment when exiting. This frees up memory for other purposes, and allows you to leave the environment as clean as possible. This is accomplished using the Remove-Variable cmdlet.
As scripts become more complex and evolve over time, it can be tough to keep track of all variables in order to remove them at the end. I created this function to help deal with this. The function takes the path of the script file, inspects the file, compiles a list of variables in the script, and runs them through the Remove-Variable cmdlet. It builds on some of the code from Auto-Documenting Script Variables.
function Remove-ScriptVariables($path) { $result = Get-Content $path | ForEach { if ( $_ -match '(\$.*?)\s*=') { $matches[1] | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'} } } ForEach ($v in ($result | Sort-Object | Get-Unique)){ Write-Host "Removing" $v.replace("$","") Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue } } # end function Get-ScriptVariables
We then call the function, passing the built-in $MyInvocation.MyCommand.Name value, which automatically contains the path and name of the currently running script. Essentially, we tell the function to run against it’s own script file:
Remove-ScriptVariables($MyInvocation.MyCommand.Name)
Donations
I’ve never been one to really solicit donations for my work. My offerings are created because *I* need to solve a problem, and once I do, it makes sense to offer the results of my work to the public. I mean, let’s face it: I can’t be the only one with that particular issue, right? Quite often, to my surprise, I’m asked why I don’t have a “donate” button so people can donate a few bucks. I’ve never really put much thought into it. But those inquiries are coming more often now, so I’m yielding to them. If you’d like to donate, you can send a few bucks via PayPal at https://www.paypal.me/PatRichard. Money collected from that will go to the costs of my website (hosting and domain names), as well as to my home lab.
I start my script with:
$DefaultVariables = $(Get-Variable).Name
and at the end I insert this line (PS V4)
((Compare-Object -ReferenceObject (Get-Variable).Name -DifferenceObject $DefaultVariables).InputObject).foreach{Remove-Variable -Name $_}
This will also remove dynamicaly created variables and variables created by a dot sourced script.
Excellent. Thanks for the info!
I stumbled across this 9 years later. So, knowing what you know after these years, would you still leave it as is or change it up at all?