Logging All Powershell Commands and Output
There have been a number of occasions where I have accidentally closed out of powershell, and had to retype a script that took some time to create, or wanted to go back to see what commands I had already run. Usually the up Arrow Key is sufficient for this, however what about commands that you ran a few days ago?
This post will walk you through setting up a powershell profile to automatically log all activity within powershell.
1. Create the Folder Path for the script output file. Mine is C:\PowershellLog
2. We need to allow the custom profile to be able to execute. This will allow Powershell to execute .ps1 scripts written by you, but will still prompt for unsigned scripts from the internet. To allow powershell to execute custom ps1 scripts, open Powershell and run the following command.
3. Next create a Powershell profile that will be loaded every time powershell is opened. Type the exact command below.
New-item -type file -path $profile -force
4. The profile can now be edited to execute custom commands at startup. This can include loading custom aliases, setting the powershell window colors, heading etc.. Today I will just be using it to setup a transcript for Powershell. To edit the profile in Notepad, type the following in Powershell.
5. This will open your profile in notepad. We can now set the default location, add a time stamp as well as a transcript file to the profile. Now every time powershell is opened, it will log the date and time, as well as append all commands and outputs to a text file. This is what the entirety of my profile looks like.
start-transcript C:\PowershellLog\PSTranscript.txt -append -noclobber
$a = Get-Date
“Date: ” + $a.ToShortDateString()
“Time: ” + $a.ToShortTimeString()
6. Save the notepad file. Now if I browse to C:\PowershellLog\PSTranscript.txt, I will see the following logged for every new powershell session I open, as well as my complete history of everything that has ever been run in powershell, as well as the associated outputs that were displayed in powershell.
Transcript started, output file is C:\PSTranscirpts.txt
Time: 1:42 PM
This will also work for Exchange Management Shell, or any other pre-baked Powershell application. Pretty cool huh? Note that this only applies to the current user. I may address doing this for multiple users at a later date. Let me know if that is something you would be interested in seeing.