powershell - Remove all variables

后端 未结 8 769
礼貌的吻别
礼貌的吻别 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:37

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

提交回复
热议问题