Date Calculation in PowerShell

When using PowerShell to schedule automated tasks, it’s very commonly needed to calculated dates, like the First Day of a Month, Last Day of Previous Month based on current date. Here are some sample of dates calculation in PowerShell

#Current Date
$CurrentDate=Get-Date

#Previous Date
$PreviousDate=$CurrentDate.AddDays(-1)

#First Day of The Month
$FirstDayOfTheMonth=Get-Date -Day 1 #First Day of This month

#Previous Month End
$PreviousMonthEnd=$FirstDayOfTheMonth.AddDays(-1) 

#First Day of Last Month
$FirstDayOfLastMonth=Get-Date -Date $PreviousMonthEnd -Day 1

#Last Business Day (Simple Logic without considering Statutory Holidays)
$LastBusinessDate=if($CurrentDate.DayOfWeek -eq "Sunday")
        {
            $CurrentDate.AddDays(-2)
        }elseif($CurrentDate.DayOfWeek -eq "Monday")
        {
            $CurrentDate.AddDays(-3)
        }else
        {
            $CurrentDate.AddDays(-1)
        }

Leave a Reply