码迷,mamicode.com
首页 > 系统相关 > 详细

PowerShell Remove all user defined variable in PowerShell

时间:2016-04-29 14:02:46      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

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

PowerShell Remove all user defined variable in PowerShell

标签:

原文地址:http://www.cnblogs.com/wushuaiyi/p/5445873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!