PowerShell Remove all user defined variable in PowerShell

When PS scripts executes, it is possibly create much user defined variables.

So, sometimes these varibales may confuse us a lot.

 

Here's a workaound:

Most of the standard variables can be found in System.Management.Automation.SpecialVariables. If you filter out these and a small list of other known variables, you can create a reusable function to get user-defined variables:

function Get-UDVariable {
  get-variable | where-object {(@(
    "FormatEnumerationLimit",
    "MaximumAliasCount",
    "MaximumDriveCount",
    "MaximumErrorCount",
    "MaximumFunctionCount",
    "MaximumVariableCount",
    "PGHome",
    "PGSE",
    "PGUICulture",
    "PGVersionTable",
    "PROFILE",
    "PSSessionOption"
    ) -notcontains $_.name) -and `
    (([psobject].Assembly.GetType('System.Management.Automation.SpecialVariables').GetFields('NonPublic,Static') | Where-Object FieldType -eq ([string]) | ForEach-Object GetValue $null)) -notcontains $_.name
    }
}

in your script, just use :

Get-UDVariable | Remove-Variable

 

One more suggestion:

I don't think it will be the best solution to solve problems made by remaining varibales.

When we create varibale in our scripts, we should have a think that what is the proper scope ?

MSDN ref : https://technet.microsoft.com/en-us/library/hh847849.aspx

posted @ 2016-04-29 12:18  Jeremy Wu  阅读(214)  评论(0编辑  收藏  举报