Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you list only user-created variables in PowerShell?

Is it possible to easily list only user-created variables in PowerShell? The get-variable Cmdlet gives me all the system variables as well which isn't what I'd like sometimes.

For example if I open a new session and do

$a=1
$b=2

I'd like some variant of get-variable that only returns a and b since they are the only two variables that have been explicitly created in the session.

like image 375
WalkingRandomly Avatar asked Aug 24 '13 13:08

WalkingRandomly


1 Answers

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
    }
}

$a = 5
$b = 10
get-udvariable

Name                           Value                                                                                                              
----                           -----                                                                                                              
a                              5     
b                              10

Note: In the ISE there are two additional standard variables: $psISE and $psUnsupportedConsoleApplications

like image 188
jon Z Avatar answered Oct 18 '22 21:10

jon Z