I want to remove all user-created variables at the start of a script.
Currently I am doing Remove-Variable -Name *
but it tries to dele
You should not rely on those variables. Anything that was not declared is just not used. If you need to pass things around, use parameters.
If you keep up to this principle, you would just overwrite your user-created variable and use it like it never existed.
This is enterprise best practices that let you infinitely scale your scripts. Not just in Powershell, but in any language which could have global variables, such as Javascript.
Invoke a new instance of PowerShell, get the built-in variables, then remove everything else that doesn't belong.
$ps = [PowerShell]::Create()
$ps.AddScript('Get-Variable | Select-Object -ExpandProperty Name') | Out-Null
$builtIn = $ps.Invoke()
$ps.Dispose()
$builtIn += "profile","psISE","psUnsupportedConsoleApplications" # keep some ISE-specific stuff
Remove-Variable (Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$builtIn -NotContains $_})
I suppose you could make a list of all the variables you don't want to delete.
$DontDelete = '$','?','^','args',...,'WhatIfPreference'
Then delete the variables that are not on the Don't Delete list.
Instead of deleting all the user variables, start a fresh instance of PowerShell:
PS C:\> $x = 10
PS C:\> $y = 50
PS C:\> $blah = 'text'
PS C:\> Write-host $x $y $blah
10 50 text
PS C:\> powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\> Write-host $x $y $blah
PS C:\>
User defined variables won't carry over into the new instance.
PS C:\> $bleh = 'blue'
PS C:\> Write-Host $bleh
blue
PS C:\> exit
PS C:\> Write-host $bleh
PS C:\>
Your variables won't carry back over into the calling instance, either.
You have a few options in terms of how to actually accomplish this.
You can always start the new instance yourself, of course:
powershell -ExecutionPolicy Unrestricted -File myscript
You can't. You'll have to keep track of the available variables before the script started and remove any variables added after the script executed.
Since all the system variables are read-only or constant anyway you can just silence the errors:
Remove-Variable * -ErrorAction SilentlyContinue
But admittedly, you should probably exclude a few anyway:
Get-Variable -Exclude PWD,*Preference | Remove-Variable -EA 0