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
functionGet-BuiltInPSVariable($Name='*') { # create a new PowerShell $ps = [PowerShell]::Create() # get all variables inside of it $null = $ps.AddScript('$null=$host;Get-Variable') $ps.Invoke() | Where-Object Name -like$Name # dispose new PowerShell $ps.Runspace.Close() $ps.Dispose() }
# create a new PowerShell $ps = [PowerShell]::Create() # get all variables inside of it $null = $ps.AddCommand('Get-Variable') $result = $ps.Invoke() # dispose new PowerShell $ps.Runspace.Close() $ps.Dispose()
classHelperStuff { # get first character of string and throw exception # when string is empty or multi-line static[char] GetFirstCharacter([string]$Text) { if ($Text.Length -eq0) { throw'String is empty' } if ($Text.Contains("`n")) { throw'String contains multiple lines' } return$Text[0] }
# get file extension in lower case static[string] GetFileExtension([string]$Path) { return [Io.Path]::GetExtension($Path).ToLower() } }
Name Value --------- Extensions [{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{0F6B957E-509E-11D1-A7CC-0000F87571E3}] Link Local Options 0 GPOLink 1 Version 65537 GPOName Guidelines of the local group lParam 0 DSPath LocalGPO FileSysPath C:\WINDOWS\System32\GroupPolicy\Machine DisplayName Guidelines of the local group