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
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 $_})