Add TimeStamp to Every Command in PowerShell

Let’s add a timestamp to every command we type in the PowerShell console.
Not sure how useful this is to absolutely everybody, but such feature was required one time and it turned out pretty good.

Like when you use the word .LOG on the first line in windows Notepad it creates a time stamp of the current time which can be useful for many reasons.

So how do we do this?

A good advice before you enter the command into PowerShell would be to grab a free copy of NotePad++ which provides an amazing tool to analyze and write several programing languages.
Click here to see how to change programing language in NotePad++

We kick it of by starting PowerShell.
Then we use the following code to add the timestamp:

function prompt {
    $dateTime = get-date -Format "dd.MM.yyyy HH:mm:ss"
	$currentDirectory = $(Get-Location)
    write-host "$dateTime" -ForegroundColor White
	write-host "PS $(Convert-Path $currentDirectory)>" -NoNewline
    return " "
}

This code can either be typed/pasted directly into the console itself, or we could paste it into a text editor and save it as a PS1 file which is associated with Powershell to make a script file.
We are not going to dive into how PS1 files work in this tutorial and will only be posting the code directly into the console for now.

When we post the code, it will look something like this due to the “{” character at the end of the first line. This character will prevent the code to execute until we add the closing character “}”

After hitting enter the timestamp will be added at the end of every command that is being typed into the PowerShell console.
In the example below we use the “ls” command (to list folder content, and yes, we know the theoretically correct way to do this in PowerShell is “Get-ChildItem” but HEY C’mon! Lets take advantage of it’s cross-platform feature).

Hint!

If you should notice that our prompt line start with “DigitalBrekke” and not the current path, it’s easily changed in the code using the following code instead:

function prompt {
    $dateTime = get-date -Format "dd.MM.yyyy HH:mm:ss"
    write-host "$dateTime" -ForegroundColor White
    write-host "YOUR TEXT HERE" -NoNewline
    return " "
}

Just change the “YOUR TEXT HERE” to what ever you want, but keep the ” characters there or else it will fail.

Also remember that once you close the PowerShell window it will all revert back to the original PowerShell display.

Thanks for reading!
Hope this was helpful for anyone..