powershell - Remove all variables

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

    Instead of deleting all the user variables, start a fresh instance of PowerShell:

    PS C:\> $x = 10
    PS C:\> $y = 50
    PS C:\> $blah = 'text'
    PS C:\> Write-host $x $y $blah
    10 50 text
    PS C:\> powershell
    Windows PowerShell
    Copyright (C) 2009 Microsoft Corporation. All rights reserved.
    
    PS C:\> Write-host $x $y $blah
    
    PS C:\>
    

    User defined variables won't carry over into the new instance.

    PS C:\> $bleh = 'blue'
    PS C:\> Write-Host $bleh
    blue
    PS C:\> exit
    PS C:\> Write-host $bleh
    
    PS C:\>
    

    Your variables won't carry back over into the calling instance, either.

    You have a few options in terms of how to actually accomplish this.

    1. You can always start the new instance yourself, of course:

      powershell -ExecutionPolicy Unrestricted -File myscript

    2. You could encode that command in a separate script and then only call that script, and not the companion one with the real code.

提交回复
热议问题