Auto-Logging Command Output

by Aug 1, 2017

In the previous tip we introduced the PreCommandLookupAction supported by PowerShell 3 and better. Today we have a special implementation for you.

When you run below code, PowerShell will accept any command that starts with “*” and log the command output in a text file. The text file opens after the command is done.

So you can now run *dir instead of dir to log the results, or *Get-Process instead of Get-Process.

$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 -eq 0)
          { & $command }
          { & $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 } 

Twitter This Tip! ReTweet this Tip!