DateTime Utility Functions

DateTime Utility Functions

Rate This
  • Comments 6

I often want to find things that happened Today.  For instance, which files got changed today.  Windows PowerShell makes this easy to do but it can be a bit verbose and I do it a lot so I've added a function to my profile:  IsToday.

function isToday ([datetime]$date)
{[datetime]::Now.Date  -eq  $date.Date}

This takes advantage of 2 things:

  1. .NET provides a NOW static property which provides the current datetime
  2. DateTimes have a DATE property which gives you just the date stripping off the specific time within that date (it always returns 12:00am).

With this you can do things like:

PS> dir > t4.txt
PS> dir |where {isToday $_.lastwritetime}

    Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          9/6/2006   8:20 AM      47086 t4.txt

 

That is great but sometimes you want to know Recent things not just the things that happened today.  For that I put together another function to deal with that:

function isWithin([int]$days, [datetime]$Date)
{
    [DateTime]::Now.AddDays($days).Date -le $Date.Date
}

Note that this doesn't deal with the case of providing dates in the future - that isn't something I do much but if you do, this function won't help you.

This is how I get all the application events that occured within the last 2 days

PS> get-eventlog application -newest 2048 |where {isWithin -2 $_.TimeWritten}

Index Time          Type Source                EventID Message
----- ----          ---- ------                ------- -------
15491 Sep 06 08:14  Erro Userenv                  1054 Windows cannot obtain the domain controller name for your com...
15490 Sep 06 08:14  Erro Userenv                  1054 Windows cannot obtain the domain controller name for your com...
15489 Sep 06 08:14  Erro Userenv                  1054 Windows cannot obtain the domain controller name for your com...

....

 

Enjoy!

Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

 

PSMDTAG:DOTNET: Datetime

PSMDTAG:FAQ: How can I find all the things that happened today?

PSMDTAG:FAQ: How can I find all the things that happened within the last x days?

Leave a Comment
  • Please add 2 and 5 and type the answer here:
  • Post
  • how would I go about copying all files modified today to a certain directory?
  • To Greg:
    You can just pipe the output file to "Copy-Item"(it looks quite graceful...)

    ls | ? {isToday $_.LastWriteTime} | Copy-Item -Destination <desitnation directory here>

    Make sure that you are not copying destination directory as well.  If you are trying to copy destination directory onto the desitnation directory, you would see an error but it's ignoreable since all the files except the destination directory will be copied.

    But if you wouldn't want to see an error message to be thrown, you can pass "SielentlyContinue" ErrorAction argument.

    ... | Copy-Item -Destination mod -ea SilentlyContinue

  • in my batch scripts i have this default process to use in varying ways.  How can I do the same thing in PS?

    now> %temp%\dt
    for /f "tokens=1-7 delims=: " %%a in (%temp%\dt) do set xDay=%%a&& set xMonth=%%b&& set xDate=%%c&& set xHour=%%d&& set xMinute=%%e&& set xSecond=%%f&& set xYear=%%g

    or can you just get rid of the special chars in the time without changing your system default seperators?
  • Mostly you don't have to do anything since datetime is an object which means you can just access it's properties:

    PS (133) > $date = get-date
    PS (134) > $date.day
    29
    PS (135) > $date.month
    9
    PS (136) > $date.year
    2006

    However, if you do have a date string string for some reason:

    PS (150) > $dateStr = [string] (get-date)
    PS (151) > $dateStr
    09/29/2006 16:56:53

    We want to split this string into pieces at the space, ':' and '/' characters. We'll use the split method to do this:

    PS (152) > $dateStr.split(" :/")
    09
    29
    2006
    16
    56
    53

    And to capture the output in variables, we use multiple assignement:

    PS (153) > $Month,$Day,$Year,$Hour,$Minute,$Second = $dateStr.split(" :/")
    PS (154) > $hour
    16
    PS (155) > $minute
    56
    PS (156) > $year
    2006

    -bruce

    Bruce Payette [MSFT]
    Windows PowerShell Tech Lead

  • You could use

      [datetime]::Today

    instead of

      [datetime]::Now.Date

  • I need this to find files\folders older than x days so I can delete them. This works great for all items for today and x days back but I just need the x days back.

Page 1 of 1 (6 items)