Looping in PowerShell forward and backwards through days

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

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:

CountBack -startDate (get-Date).AddDays(-12) -daysToSkip 15 -endDate (get-Date).AddDays(-100)

Countforward

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:

CountForward -startDate (get-Date).AddDays(-300) -daysToSkip 15 -endDate (get-Date).AddDays(-40)

One thought to “Looping in PowerShell forward and backwards through days”

Leave a Reply to PK Cancel reply