如何在PowerShell中仅列出用户创建的变量?

Wal*_*mly 7 powershell scripting

是否可以在PowerShell中轻松列出用户创建的变量?该get-variableCmdlet的给了我所有的系统变量,以及这是不是有时想我.

例如,如果我打开一个新会话并执行

$a=1
$b=2
Run Code Online (Sandbox Code Playgroud)

我想的一些变种get-variable,只有收益ab因为他们已经在会议上明确创建的仅有的两个变量.

jon*_*n Z 12

大多数标准变量都可以在System.Management.Automation.SpecialVariables.如果过滤掉这些以及其他已知变量的一小部分,则可以创建可重用的函数来获取用户定义的变量:

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
Run Code Online (Sandbox Code Playgroud)

注意:在ISE中还有两个额外的标准变量:$ psISE和$ psUnsupportedConsoleApplications


Bar*_*ekB 5

您可以考虑使用 description,但这在创建变量时需要不同的语法:

New-Variable -Name a -Value 1 -Description MyVars
nv b 2 -des MyVars
Get-Variable | where { $_.Description -eq 'MyVars' }
Run Code Online (Sandbox Code Playgroud)

第二种语法使用别名/位置参数来缩短您的工作。