Remove all user defined variables without restarting the PowerShell Console or ISE

Recently, fellow Microsoft MVP Mickey Gousset asked me how to remove existing user defined variables from the PowerShell ISE (Integrated Scripting Environment) before running a script a second time without having to restart the ISE.

While you could keep track of the variables you've used within your script to remove them once the script completes with the Remove-Variable cmdlet or by deleting them from the variable PSDrive, that can be a less than desirable solution for long and complicated scripts that define lots of variables. You could also save your script as a PS1 file and run the PS1 file instead of running it interactively in the ISE. If the PS1 file is run, the variables will be defined in the script scope by default and when the script completes, the script scope is removed along with the variables as long as you haven't coerced them into the global scope.

A better solution is to use a variable to either store a list of the default variables when PowerShell starts or before your script runs. Be sure you understand the precedence of the different PowerShell profiles since you maybe defining variables in some of your profiles that you don't want to remove. See my blog article PowerShell $Profile: The six options and their precedence.

I'll place the following code in my profile for the ISE ($profile.AllUsersCurrentHost or $profile.CurrentUserCurrentHost from within the ISE):

1$StartupVars = @()
2$StartupVars = Get-Variable | Select-Object -ExpandProperty Name

Not sure where the profile is or how to add this code to it? The following code can be used to automatically add the necessary items to the all users ISE profile:

 1if ($Host.Name -eq 'Windows PowerShell ISE Host') {
 2    if (-not(Test-Path -Path $profile.AllUsersCurrentHost)) {
 3        New-Item -Path $profile.AllUsersCurrentHost -ItemType File
 4    }
 5    if (-not(Get-Content -Path $profile.AllUsersCurrentHost |
 6             Select-String -SimpleMatch '$StartupVars = Get-Variable | Select-Object -ExpandProperty Name')) {
 7        Add-Content -Path $profile.AllUsersCurrentHost -Value '
 8$StartupVars = @()
 9$StartupVars = Get-Variable | Select-Object -ExpandProperty Name'
10    }
11}
12else {
13    Write-Warning -Message 'This code can only be run from within the PowerShell ISE'
14}

This could even be taken a step further and turned unto a function to add those two lines of code to any of the available profiles. I've removed the check to make sure it's run in the ISE since the same process could be used to remove user defined variables in the console.

 1#Requires -Version 3.0
 2function Add-MrStartupVariable {
 3
 4<#
 5.SYNOPSIS
 6    Add variable for list of startup variables.
 7
 8.DESCRIPTION
 9    Add variable for list of startup variables to the specified PowerShell profile. Create the specified PowerShell
10    profile if it does not exist. Only adds the variable and code to populate the variable if it does not already exist.
11    Designed to be used in conjunction with Remove-MrUserVariable.
12
13.PARAMETER Location
14    Location of the PowerShell profile to add the startup variable to.
15
16.EXAMPLE
17     Add-MrStartupVariable -Location AllUsersCurrentHost
18
19.INPUTS
20    None
21
22.OUTPUTS
23    None
24
25.NOTES
26    Author:  Mike F Robbins
27    Website: http://mikefrobbins.com
28    Twitter: @mikefrobbins
29#>
30
31    [CmdletBinding(SupportsShouldProcess)]
32    param (
33        [Parameter(Mandatory)]
34        [ValidateSet('AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost')]
35        $Location
36    )
37
38    $Content = @'
39$StartupVars = @()
40$StartupVars = Get-Variable | Select-Object -ExpandProperty Name
41'@
42
43    if (-not(Test-Path -Path $profile.$Location)) {
44        New-Item -Path $profile.$Location -ItemType File |
45        Set-Content -Value $Content
46    }
47    elseif (-not(Get-Content -Path $profile.$Location |
48             Select-String -SimpleMatch '$StartupVars = Get-Variable | Select-Object -ExpandProperty Name')) {
49        Add-Content -Path $profile.$Location -Value "`r`n$Content"
50    }
51    else {
52        Write-Verbose -Message "`$StartupVars already exists in '$($profile.$Location)'"
53    }
54
55}

Write a script defining whatever variables you want. Run the script interactively by pressing F5 from within the ISE. I'll use the following code for simplicity:

1$Processes = Get-Process
2$Services = Get-Service

My first thought was to use the Compare-Object cmdlet, retrieve a new list of all the variables, compare that list to the original, and remove the results. That's a little more complicated than simply getting a list of variables while excluding the original ones and then simply piping the results to Remove-Variable:

1Get-Variable -Exclude $StartupVars |
2Remove-Variable -Force

I'll turn that code into a function so I can simply call it without having to remember any syntax or the variable name:

 1#Requires -Version 3.0
 2function Remove-MrUserVariable {
 3
 4<#
 5.SYNOPSIS
 6    Removes user defined variables.
 7
 8.DESCRIPTION
 9    Removes user defined variables from the PowerShell ISE or console. $StartupVars must be defined prior to running
10    this function, preferably in a profile script. Populate $StartUpVars with 'Get-Variable | Select-Object -ExpandProperty
11    Name'. All variables added after populating $StartupVars will be removed when this function is run.
12
13.EXAMPLE
14     Remove-MrUserVariable
15
16.INPUTS
17    None
18
19.OUTPUTS
20    None
21
22.NOTES
23    Author:  Mike F Robbins
24    Website: http://mikefrobbins.com
25    Twitter: @mikefrobbins
26#>
27
28    [CmdletBinding(SupportsShouldProcess)]
29    param ()
30
31    if ($StartupVars) {
32        $UserVars = Get-Variable -Exclude $StartupVars -Scope Global
33
34        foreach ($var in $UserVars){
35            try {
36                Remove-Variable -Name $var.Name -Force -Scope Global -ErrorAction Stop
37                Write-Verbose -Message "Variable '$($var.Name)' has been successfully removed."
38            }
39            catch {
40                Write-Warning -Message "An error has occured. Error Details: $($_.Exception.Message)"
41            }
42
43        }
44
45    }
46    else {
47        Write-Warning -Message '$StartupVars has not been added to your PowerShell profile'
48    }
49
50}

Running the function with the Verbose parameter shows that the two previously defined variables have been successfully removed:

1Remove-MrUserVariable -Verbose

remove-vars1a.jpg

The functions shown in this blog article can be installed from the PowerShell Gallery as part of my MrToolkit PowerShell module (version 1.3 and higher) with the Install-Module cmdlet that is part of the PowerShellGet module. PowerShellGet exists by default on PowerShell version 5.0 and higher and can be downloaded for PowerShell version 3.0 and higher.

1Find-Module -Name MrToolKit
2Find-Module -Name MrToolKit | Install-Module -Force

install-mrtoolkit1a.jpg

The functions shown in this blog article have also been added to my PowerShell repository on GitHub.

µ