Modification in Remove-ScriptVariables by http://www.ehloworld.com/247
2016-05-22 Leave a comment
I tried to use the script created at Function: Remove-ScriptVariables – Cleaning Up Script Variables in PowerShell by Pat Richard
There seemed a issue which makes this script unusable. I then made some changes in it. Changes added are for removing ‘SCRIPT‘ from variable names and cleaning the variables in the defined scope of the script.
function Remove-ScriptVariables() { Param( [string]$path, [string]$scope ) $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 -Name:($v.replace("$","").replace("SCRIPT:","")) ` -Scope:Script -ErrorAction:SilentlyContinue } } # end function Remove-ScriptVariables
Do ‘Get-Help Remove-variable -full | more’ to know what needs to be passed for Scope. Usually “SCRIPT” should be passed. This function can also be called at end of a function for better control with scope being defined as “LOCAL”. An example of using it as follows. This will remove script level variables created inside the script. Variables created inside a function will anyway be not accessible outside. ‘main’ is the function where I usually keep all my code.
try { main }finally{ Remove-ScriptVariables -path:$MyInvocation.MyCommand.Name -scope:"SCRIPT" }
Recent Comments