Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Create Timestamp log in PowerShell

Posted on May 21, 2006August 5, 2009

Very often in administrative scripting you will want to create a log file where the filename is a timestamp like 200605201912.log. Since PowerShell is based on .NET Framework objects, we can take advantage of the DateTime object which is obtained by using the Get-Date cmdlet:

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

PS C:\> get-dateSunday, May 21, 2006 6:47:03 PM
If we create a variable with this cmdlet, we have access to all of the object's properties.

PS C:\> $now=get-date
PS C:\> $now|get-member -membertype properties
TypeName: System.DateTimeName MemberType Definition
---- ---------- ----------
DisplayHint NoteProperty Microsoft.PowerShell.Commands.DisplayHintType
D
Date Property System.DateTime Date {get;}
Day Property System.Int32 Day {get;}
DayOfWeek Property System.DayOfWeek DayOfWeek {get;}
DayOfYear Property System.Int32 DayOfYear {get;}
Hour Property System.Int32 Hour {get;}
Kind Property System.DateTimeKind Kind {get;}
Millisecond Property System.Int32 Millisecond {get;}
Minute Property System.Int32 Minute {get;}
Month Property System.Int32 Month {get;}
Second Property System.Int32 Second {get;}
Ticks Property System.Int64 Ticks {get;}
TimeOfDay Property System.TimeSpan TimeOfDay {get;}
Year Property System.Int32 Year {get;}
DateTime ScriptProperty System.Object DateTime {get=if

PS C:\>

With this object we can build a timestamp name by returning the year, month, day and minute properties. We can even go so far as to get second and millisecond if we need that level of precision. To simplify the process, I've written a function called logstamp that will return a timestamp in the form of YearMonthDayMinute.

Function logstamp {
$now=get-Date
$yr=$now.Year.ToString()
$mo=$now.Month.ToString()
$dy=$now.Day.ToString()
$hr=$now.Hour.ToString()
$mi=$now.Minute.ToString()
if ($mo.length -lt 2) {
$mo="0"+$mo #pad single digit months with leading zero
}
if ($dy.length -lt 2) {
$dy="0"+$dy #pad single digit day with leading zero
}
if ($hr.length -lt 2) {
$hr="0"+$hr #pad single digit hour with leading zero
}
if ($mi.length -lt 2) {
$mi="0"+$mi #pad single digit minute with leading zero
}
write-output $yr$mo$dy$hr$mi

}

I'm using the ToString method to convert the datetime object into a string. I do that so that I can check the length property of the month, day and minute variables. If the length is less than 2 then I want to pad it with a leading zero. This makes all my filenames line up neatly.

When I enter this function into PowerShell I can call it at any time and it will return a timestamp string.

PS C:\> logstamp
200605211853

To build a variable for the filename we use something like this:

PS C:\> $stamp=logstamp
PS C:\> $filename=$stamp+".log"

PS C:\> $filename
200605211855.log

I can now use the $filename variable to create the log file using the New-Item cmdlet.

PS C:\> new-item . -name $filename -type "file" -value "Audit Log
"
Directory: Microsoft.PowerShell.Core\FileSystem::C:\
Mode LastWriteTime Length Name
---- ------------- ------
----
-a--- 5/21/2006 6:57 PM 9 200605211855.log
PS C:\> get-content $filename
Audit Log

PS C:\>

If you find yourself using this feature, you may want to put the function in your PowerShell profile so that it is always available.

Technorati tags:
PowerShell
Scripting


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

5 thoughts on “Create Timestamp log in PowerShell”

  1. /\/\o\/\/ says:
    May 23, 2006 at 12:00 pm

    hiya, Jeff

    you can also call the toString on the dateTime object and format it with that :

    (get-date).toString(‘yyyyMMddhhmm’)

    greetings /\/\o\/\/

  2. Jeffery Hicks says:
    May 23, 2006 at 12:40 pm

    Well that’s a whole heckuva lot easier!

  3. Jeffery Hicks says:
    May 23, 2006 at 12:47 pm

    Let me take a moment and revise the spirit of the post then. To create a logstamp function you could use code like this:

    PS C:\> Function logstamp {
    >> (get-date).toString(‘yyyMMddhhmmss’)
    >> }
    >>
    PS C:\> logstamp
    20060523124043
    PS C:\> $logfile=(logstamp)+”.log”
    PS C:\> $logfile
    20060523124123.log
    PS C:\>

    I’ve created a function called ‘logstamp’. When it is invoked you see the time stamp output. To create a logfile name I could use in a script or other command, create a new variable, $logfile, that is set to the results of logstamp plus .log. $logfile shows the finished result.

  4. Anonymous says:
    February 19, 2007 at 6:06 pm

    if you want to pad. you can also do:

    (get-date).get_Month().tostring().padleft(2,”0″)

  5. Winston says:
    March 6, 2008 at 11:52 am

    I use HH instead of hh so that I get 24 hour time and don’t have to worry about AM/PM. That way all my timestamped files sort nicely.

    I use:

    (get-date).ToString(“yyyy-MM-dd-HH-mm-ss”)

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d