powershell - Remove all variables

后端 未结 8 767
礼貌的吻别
礼貌的吻别 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: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!"
        }

提交回复
热议问题