functionGet-UserVariable($Name = '*') { # these variables may exist in certain environments (like ISE, or after use of foreach) $special = 'ps','psise','psunsupportedconsoleapplications', 'foreach', 'profile'
$ps = [PowerShell]::Create() $null = $ps.AddScript('$null=$host;Get-Variable') $reserved = $ps.Invoke() | Select-Object-ExpandProperty Name $ps.Runspace.Close() $ps.Dispose() Get-Variable-Scope Global | Where-Object Name -like$Name | Where-Object { $reserved-notcontains$_.Name } | Where-Object { $special-notcontains$_.Name } | Where-Object Name }
现在可以很容易查找所有由您(或您的脚本)创建并仍然停留在内存中的变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
PS> Get-UserVariable
Name Value --------- hash {Extensions, Link, Options, GPOLink...} prop lParam reserved {$, ?, ^, args...} result {System.Management.Automation.PSVariable, System.Management.Automation.Ques... varCount 43
PS> Get-UserVariable-Name pr*
Name Value --------- prop lParam
如果要清理您的运行空间,您可以用一行代码清除所有变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
PS> Get-UserVariable
Name Value --------- hash {Extensions, Link, Options, GPOLink...} key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\H... prop lParam reserved {$, ?, ^, args...} result {System.Management.Automation.PSVariable, System.Management.Automation.Ques... varCount 43