$ExecutionContext.SessionState.InvokeCommand.PreCommandLookupAction = { # is called whenever a command is ready to execute param($command, $eventArgs)
# check commands that start with "*" and were not # executed internally by PowerShell if ($command.StartsWith('*') -and$eventArgs.CommandOrigin -eq'Runspace') { # save command output here $debugPath = "$env:temp\debugOutput.txt" # clear text file if it exists $exists = Test-Path$debugPath if ($exists) { Remove-Item-Path$debugPath } # remove leading "*" from a command name $command = $command.Substring(1) # tell PowerShell what to do instead of # running the original command $eventArgs.CommandScriptBlock = { # run the original command without "*", and # submit original arguments if there have been any $( if ($args.Count -eq0) { & $command } else { & $command$args } ) | # log output to file Tee-Object-FilePath$debugPath | # open the file once all output has been processed ForEach-Object-Process { $_ } -End { if (Test-Path$debugPath) { notepad $debugPath } } }.GetNewClosure() } }
$ExecutionContext.SessionState.InvokeCommand.PreCommandLookupAction = { # is called whenever a command is ready to execute param($command, $eventArgs)
# not executed internally by PowerShell if ($command-eq'Get-Service'-and$eventArgs.CommandOrigin -eq'Runspace') { # tell PowerShell what to do instead of # running the original command $eventArgs.CommandScriptBlock = { # run the original command without "*", and # submit original arguments if there have been any $command = 'dir'
$code = { # submit the host process RawUI interface and the execution context param($RawUi, $ExecContext)
do { # find the current location in the host process $location = $ExecContext.SessionState.Path.CurrentLocation # compose the time and date display $time = Get-Date-Format'HH:mm:ss dddd MMMM d' # compose the title bar text $title = "$location$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).AddArgument($ExecutionContext) $handle = $ps.BeginInvoke()
$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.”异常。