powershell - Remove all variables

后端 未结 8 731
礼貌的吻别
礼貌的吻别 2020-12-31 05:05

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

8条回答
  •  天涯浪人
    2020-12-31 05:48

    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.

提交回复
热议问题