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
Here is a hack that will delete all variables except those created in your $profile. Note that this takes a few seconds to run, and there's a pretty good chance you could achieve your end goal in a more efficient way. You'll have to adjust the "15" in the select statement to correspond to the number of lines your profile script spits out. Or you could modify it to search for the first line from gv (get-variable).
$x=powershell -nologo -command "gv|out-string"
$y=($x|select -skip 15) -split "\s+",2
$varnames = $(for ($i=0;$i -lt $y.length; $i+=2) { $y[$i]})
rv i,x,y
gv | % {if ($varnames -notcontains $_.name) {rv $_.name -EA 0}}
Caveat: this won't delete variables created by Powershell hosts that specify an InitialSessionState that loads modules or executes scripts that create variables. However for normal Powershell and powershell_ise you don't have to worry about that.