Get-Date Math

Welcome Forums General PowerShell Q&A Get-Date Math

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

  • Author
  • #5522

    Points: 0
    Rank: Member

    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

The topic ‘Get-Date Math’ is closed to new replies.