How do you specify only user variables in PowerShell?

Is it easy to list only user-created variables in PowerShell? The get-variable cmdlet also gives me all the system variables that I sometimes don’t like.

For example, if I open a new session and do

 $a=1 $b=2 

I need some kind of get-variable that returns only a and b , since they are the only two variables that were explicitly created in the session.

+7
scripting powershell
source share
3 answers

Most standard variables can be found in System.Management.Automation.SpecialVariables . If you filter them and a short list of other known variables, you can create a reusable function to get custom 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 ISE has two additional standard variables: $ psISE and $ psUsupportedConsoleApplications

+11
source share

You might consider using a description, but to create variables, you need a different syntax:

 New-Variable -Name a -Value 1 -Description MyVars nv b 2 -des MyVars Get-Variable | where { $_.Description -eq 'MyVars' } 

The second syntax uses aliases / positional parameters to shorten your work.

+4
source share

The only way I personally can do this will require an additional step of storing the variables in the array.

One example, just for testing:

 PS C:\Users\Athomsfere> $myVars = @($a, $b) PS C:\Users\Athomsfere> Get-Variable -Name myVars Name Value ---- ----- myVars {some, thing} 
+1
source share

All Articles