loop backwards through current month

Copper Contributor

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. 



 

#Connect to Exchange Online
Connect-ExchangeOnline -ShowBanner:$False
 
$StartRemove = -1
$EndRemove = $StartRemove+1

#Set Date Filters - past 24 hours
$StartDate = ((Get-Date).Date).AddDays($StartRemove)
$EndDate = (Get-Date).Date.AddDays($EndRemove)
 
#Filter Audit log to Find specific operations
$SiteURLs = @("https://company.sharepoint.com/")
$Date = ((Get-Date).Date).AddDays(-1) -Format "yyyy-MM-dd"
$CSVFile = "C:\Temp\"+$Date+".csv"
$FileAccessOperations = @('PageViewed')
$SharePointLog = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -Operations $FileAccessOperations -ResultSize 5000 -ObjectIds $SiteURLs
$AuditLogResults = $SharePointLog.AuditData | ConvertFrom-Json | Select CreationTime,UserId,Operation, ObjectID,SiteUrl,SourceFileName,ClientIP

#Export Audit log results to CSV
$AuditLogResults
$AuditLogResults | Export-csv -Path $CSVFile  -NoTypeInformation
 
#Disconnect Exchange Online
Disconnect-ExchangeOnline

 


I image it will look something like this 

 

for ($EndDate = (Get-Date).Date; $EndDate -eq "01 November 2023 00:00:00"; (Get-Date).Date.AddDays(-1)) 

{

Write-Host The value of Var is: $EndDate

}

 


 

1 Reply

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