Function: Remove-ScriptVariables – Cleaning Up Script Variables in PowerShell
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)




Follow Me