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 2 | $StartupVars = @() $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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | if ($Host.Name -eq 'Windows PowerShell ISE Host') { if (-not(Test-Path -Path $profile.AllUsersCurrentHost)) { New-Item -Path $profile.AllUsersCurrentHost -ItemType File } if (-not(Get-Content -Path $profile.AllUsersCurrentHost | Select-String -SimpleMatch '$StartupVars = Get-Variable | Select-Object -ExpandProperty Name')) { Add-Content -Path $profile.AllUsersCurrentHost -Value ' $StartupVars = @() $StartupVars = Get-Variable | Select-Object -ExpandProperty Name' } } else { Write-Warning -Message 'This code can only be run from within the PowerShell ISE' } |
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #Requires -Version 3.0 function Add-MrStartupVariable { <# .SYNOPSIS Add variable for list of startup variables. .DESCRIPTION Add variable for list of startup variables to the specified PowerShell profile. Create the specified PowerShell profile if it does not exist. Only adds the variable and code to populate the variable if it does not already exist. Designed to be used in conjunction with Remove-MrUserVariable. .PARAMETER Location Location of the PowerShell profile to add the startup variable to. .EXAMPLE Add-MrStartupVariable -Location AllUsersCurrentHost .INPUTS None .OUTPUTS None .NOTES Author: Mike F Robbins Website: http://mikefrobbins.com Twitter: @mikefrobbins #> [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory)] [ValidateSet('AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost')] $Location ) $Content = @' $StartupVars = @() $StartupVars = Get-Variable | Select-Object -ExpandProperty Name '@ if (-not(Test-Path -Path $profile.$Location)) { New-Item -Path $profile.$Location -ItemType File | Set-Content -Value $Content } elseif (-not(Get-Content -Path $profile.$Location | Select-String -SimpleMatch '$StartupVars = Get-Variable | Select-Object -ExpandProperty Name')) { Add-Content -Path $profile.$Location -Value "`r`n$Content" } else { Write-Verbose -Message "`$StartupVars already exists in '$($profile.$Location)'" } } |
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 2 | $Processes = Get-Process $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:
1 2 | Get-Variable -Exclude $StartupVars | Remove-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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #Requires -Version 3.0 function Remove-MrUserVariable { <# .SYNOPSIS Removes user defined variables. .DESCRIPTION Removes user defined variables from the PowerShell ISE or console. $StartupVars must be defined prior to running this function, preferably in a profile script. Populate $StartUpVars with 'Get-Variable | Select-Object -ExpandProperty Name'. All variables added after populating $StartupVars will be removed when this function is run. .EXAMPLE Remove-MrUserVariable .INPUTS None .OUTPUTS None .NOTES Author: Mike F Robbins Website: http://mikefrobbins.com Twitter: @mikefrobbins #> [CmdletBinding(SupportsShouldProcess)] param () if ($StartupVars) { $UserVars = Get-Variable -Exclude $StartupVars -Scope Global foreach ($var in $UserVars){ try { Remove-Variable -Name $var.Name -Force -Scope Global -ErrorAction Stop Write-Verbose -Message "Variable '$($var.Name)' has been successfully removed." } catch { Write-Warning -Message "An error has occured. Error Details: $($_.Exception.Message)" } } } else { Write-Warning -Message '$StartupVars has not been added to your PowerShell profile' } } |
Running the function with the Verbose parameter shows that the two previously defined variables have been successfully removed:
1 | Remove-MrUserVariable -Verbose |
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.
1 2 | Find-Module -Name MrToolKit Find-Module -Name MrToolKit | Install-Module -Force |
The functions shown in this blog article have also been added to my PowerShell repository on GitHub.
µ
This is really neat, thanks a lot !
Quick question about syntax. In the Add function, you have
$Content = @’
$StartupVars = @()
$StartupVars = Get-Variable | Select-Object -ExpandProperty Name
‘@
I’m not familiar with the @’ xx ‘ syntax. I get that you created an array with all of the current variables with
$StartupVars = @()
$StartupVars = Get-Variable | Select-Object -ExpandProperty Name
(although I would have expected += on the second line, not just =), but what is happening when you add that array to $Content?
Partially answered my own question. It’s a here string, which I never use, probably because I don’t really understand them.
Exactly what is happening there? I’m probably wrong, but it seems to me that $Content is basically unnecessary. You could have just used $StartupVars, couldn’t you?
Using a here string allows the function to inject the following code into your PowerShell profile.
$StartupVars = @()
$StartupVars = Get-Variable | Select-Object -ExpandProperty Name