DateTime Utility Functions

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?