Elomis Elomis - 3 months ago 29
PowerShell Question

Midnight last Monday in Powershell

I'm trying to hack up a script that returns the amount of email received to and sent from certain mailboxes today, this week and this month. I wrote this and felt good about myself until I realised my logic was wrong and it was returning the last 24 hours (get-date.(adddays(-1)) and last 7 consecutive 24 hour periods (get-date.adddays(-7)) etc.

Figuring out the first day of the month to count from wasn't that hard, found a snippet to copy

$firstDayOfMonth = Get-Date ((("01/" + (Get-Date $today).Month).ToString() + "/" + ((Get-Date $today).Year).ToString() + " 00:00:00"))


which starts with 01/ and adds today's month and years as string then appends midnight time and bundles the whole thing into a system.time object, but I can't do that with the week.

System.time objects have a .DayOfWeek property and I can switch that to figure out how many days we are from last Monday, and I have a $Monday variable that contains this time last Monday, how do I modify that variable to refer to midnight last Monday?

Answer

First Monday of the Month

do {
    $n++
    $date = (date -Hour 0 -Minute 0 -Second 0).AddDays(-$n)
}
Until ( `
    $date.DayOfWeek -eq "Monday" -and `
    $date.Day -le 7 `
)

First Monday of the Week

$n = 0
do {
    $date = (date -Hour 0 -Minute 0 -Second 0).AddDays(-$n)
    $n++
}
Until ( $date.DayOfWeek -eq "Monday" )
Comments