powershell - Remove all variables powershell - Remove all variables powershell powershell

powershell - Remove all variables


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


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 stuffRemove-Variable (Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$builtIn -NotContains $_})


Instead of deleting all the user variables, start a fresh instance of PowerShell:

PS C:\> $x = 10PS C:\> $y = 50PS C:\> $blah = 'text'PS C:\> Write-host $x $y $blah10 50 textPS C:\> powershellWindows PowerShellCopyright (C) 2009 Microsoft Corporation. All rights reserved.PS C:\> Write-host $x $y $blahPS C:\>

User defined variables won't carry over into the new instance.

PS C:\> $bleh = 'blue'PS C:\> Write-Host $blehbluePS C:\> exitPS C:\> Write-host $blehPS 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.

  1. You can always start the new instance yourself, of course:

    powershell -ExecutionPolicy Unrestricted -File myscript

  2. You could encode that command in a separate script and then only call that script, and not the companion one with the real code.