PowerShell Remove all user defined variable in PowerShell

Source: Internet
Author: User

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

So, sometimes these varibales could confuse us a lot.

Here's a workaound:

Most of the variables can is 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

functionget-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'll be the best solution to solve problems made by remaining varibales.

When we are create varibale in our scripts, we should has a think what's the proper scope?

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

PowerShell Remove all user defined variable in PowerShell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.