$code = { # submit the host process RawUI interface and the execution context param($RawUi)
do { # compose the time and date display $time = Get-Date-Format'HH:mm:ss dddd MMMM d' # compose the title bar text $title = "Current Time: $time" # output the information to the title bar of the host process $RawUI.WindowTitle = $title # wait a half second Start-Sleep-Milliseconds500 } while ($true) } $ps = [PowerShell]::Create() $null = $ps.AddScript($code).AddArgument($host.UI.RawUI) $handle = $ps.BeginInvoke()
但是对某些 DLL 文件,这个命令会执行失败,PowerShell 返回一个““Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.”异常。
当您在 Windows 机器上的 “Windows PowerShell” 中运行这段脚本,将会报错:
1 2 3 4 5 6 7 8 9
PS> C:\Users\abc\requires core.ps1 The script 'requires core.ps1' cannot be run because it contained a "#requires" statement for PowerShell editions 'Core'. The edition of PowerShell that is required by the script does not match the currently running PowerShell Desktop edition. + CategoryInfo : NotSpecified: (requires core.ps1:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSEdition
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() }