I was searching for a way for looping in PowerShell forward and backwards through days every 15 days. So I thought I would share it with you guys.
I have two different samples. Both samples have the option to specify the number of the days to skip in each loop.
The first one is counting back in days until a specific day and the second is counting forward.
Countback
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Function CountBack { Param([datetime]$startDate,[int]$daysToSkip,[datetime]$endDate) Write-Host "Count back from:" $startDate.ToString("yyyy-MM-dd") Write-Host "Count back until:" $endDate.ToString("yyyy-MM-dd") Write-Host "Count every" $daysToSkip "day(s)" while ($startDate -ge $endDate) { Write-Host $startDate.ToString("yyyy-MM-dd") # Execute your code here $startDate = $startDate.AddDays(-$daysToSkip) } } |
Execute the command with:
1 |
CountBack -startDate (get-Date).AddDays(-12) -daysToSkip 15 -endDate (get-Date).AddDays(-100) |
Countforward
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Function CountForward { Param([datetime]$startDate,[int]$daysToSkip,[datetime]$endDate) Write-Host "Count forward from:" $startDate.ToString("yyyy-MM-dd") Write-Host "Count forward until:" $endDate.ToString("yyyy-MM-dd") Write-Host "Count every" $daysToSkip "day(s)" while ($startDate -le $endDate) { Write-Host $startDate.ToString("yyyy-MM-dd") # Execute your code here $startDate = $startDate.AddDays($daysToSkip) } } |
Execute the command with:
1 |
CountForward -startDate (get-Date).AddDays(-300) -daysToSkip 15 -endDate (get-Date).AddDays(-40) |
Thanks It was nice for Search-UnifiedAuditLog start enddate