Get-Date Math

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 6 years, 5 months ago.

  • Author
  • #5522

    by GregSmith at 2013-02-07 05:24:45

    Ok....I think I'm trying to make Get-Date math harder than it really is.......

    I'm fine doing stuff like this:

    $24HoursAgo = [DateTime]::Now.AddHours(-24)
    $Events = Get-Eventlog -New 1024 security | Where {$24HoursAgo -le $_.TimeWritten}
    $Events | Format-Table index, timewritten, message -wrap -Auto

    BUT.... What if I wanted to pull the same type info but only between the hours of 10pm and 2am. Of course this means spanning two days.... Is it possible to do an "and" in the "where" clause? What I've tried, so far, fails....

    by kittH at 2013-02-07 05:55:47

    $24HoursAgo = [DateTime]::Now.AddHours(-24)
    $12HoursAgo = (Get-Date).AddHours(-12)
    $Events = Get-Eventlog -New 1024 security | Where {($24HoursAgo -le $_.TimeWritten) -and ($12HoursAgo -gt $_.TimeWritten)}
    $Events | Format-Table index, timewritten, message -wrap -Auto

    Parenthesis around the expressions you want to evaluate with -and in between if you're going to use "Where-Object"

    However, Get-Eventlog has filters built in for datetime and filtering during is usually far more efficient than filtering after the query.
    $Events = Get-Eventlog -New 1024 security -Before $12HoursAgo -After $24HoursAgo

    by GregSmith at 2013-02-07 06:14:47

    The Before and After filters were just what I was hoping for! Much more simple.....THANKS!

    by GregSmith at 2013-02-07 07:25:46

    For anyone interested.... Here's how I applied the suggested fix.......

    $start = get-date '2/6/13 10:00:00 PM'
    $end = get-date '2/7/13 2:00:00 AM'
    get-eventlog -log security -after $start -Before $end| Format-Table index, timewritten, message -wrap -Auto

You must be logged in to reply to this topic.