powershell - Remove all variables

后端 未结 8 727
礼貌的吻别
礼貌的吻别 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.

    0 讨论(0)
  • 2020-12-31 05:49

    I would pull the list of existing variable names into an array at the beginning of the script, then remove any newly added variables at the end of the script:

    ### Start of script (store list of existing variable names)
    $ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name
    
    <#
    Script contents go here
    #>
    
    ### End of script (remove new variables)
    $NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
    if ($NewVariables)
        {
        Write-Host "Removing the following variables:`n`n$NewVariables"
        Remove-Variable $NewVariables
        }
    else
        {
        Write-Host "No new variables to remove!"
        }

    0 讨论(0)
提交回复
热议问题