$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() } }