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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With