Logging Input Commands

by Nov 26, 2012

If you'd like to maintain a log file with all the commands you entered interactively – in the PowerShell console as well as in the ISE editor – here is an easy way:

Simply redefine the built-in prompt function. It is responsible for writing the prompt text. Since it gets called automatically AFTER each command you enter, you can add code to log the last command. The last command is available from Get-History.

Here is an example of such a function. It also shortens the prompt text and instead displays the current location in the window title bar.

function prompt
{
  'PS> '
  $Host.UI.RawUI.WindowTitle = Get-Location
  if ($global:CmdLogFile) {
      Get-History -Count 1 | 
        Select-Object -ExpandProperty CommandLine  | 
        Out-File $global:CmdLogFile -Append
  }
}

To enable logging, set $global:CmdLogFile to a path, like this:

$global:CmdLogFile = "$env:temp\logfile.txt"

Now, all commands you enter are written to this file. To disable logging, remove the variable:

Remove-Variable CmdLogFile -Scope global

Twitter This Tip! ReTweet this Tip!