Forum Discussion
NickMumby
Nov 30, 2023Copper Contributor
loop backwards through current month
I have a script to pull audit logs from the O365 compliance centre. I'd like to use the script in a loop that I can run at the end of the month, executing once for each day until the 1st is reached. ...
Andres-Bohren
Dec 03, 2023Steel Contributor
Hi NickMumby
How about this Code.
$CurrentDate = Get-Date -Hour 0 -Minute 0 -Second 0
$MonthAgo = $CurrentDate.AddMonths(-1)
$FistDayOfMonth = Get-Date $MonthAgo -Day 1
$FistDayOfMonth
$DaysInMonth = [datetime]::DaysInMonth($MonthAgo.Year,$MonthAgo.Month)
for ($i = 0; $i -lt $DaysInMonth; $i++) {
Write-Host "The Iteration Number is: $i"
$StartDate = ($FistDayOfMonth).AddDays(+$I)
$EndDate = $StartDate.AddDays(+1)
[string]$StartDateStr = ($StartDate).ToString("yyyy-MM-dd")
[string]$EndDateStr = ($EndDate).ToString("yyyy-MM-dd")
Write-Host "Start: $StartDateStr EndDate: $EndDateStr"
##Do your thing here
}
Hope this helps.
Kind Regards
Andres
Hope this helps.
Kind Regards
Andres