Thursday, January 6, 2011

Determine the Last Day of the Month in PowerShell

I run into situations where I need to export mailboxes using Export-Mailbox and need to break up the returned PST files by month. To do this, I need to know the start of the month (easy) and the end of the month (not as easy). This is how I generate that DateTime variable.
$date = "02/15/2008" # Using a date in a leap year for fun
$firstDayOfMonth = Get-Date ((((Get-Date $date).Month).ToString() + "/1/" + ((Get-Date $date).Year).ToString() + " 00:00:00"))
$lastDayOfMonth = ((Get-Date ((((Get-Date $firstDayOfMonth).AddMonths(1)).Month).ToString() + "/1/" + (((Get-Date $firstDayOfMonth).AddMonths(1)).Year).ToString()))) - (New-TimeSpan -seconds 1)
Write-Host ("-StartDate " + (Get-Date $firstDayOfMonth -format d) + " -EndDate " + (Get-Date $lastDayOfMonth -format d))

6 comments:

  1. this is perfect; TY very much

    ReplyDelete
  2. Here's a simpler solution

    $myDate = (Get-Date -Year 2008 -Month 2 -Day 15).Date

    $firstDayOfMonth = $myDate.AddDays( - $myDate.Day + 1)
    $lastDayOfMonth = $mydate.AddMonths(1).AddDays( - $myDate.Day )

    ReplyDelete
  3. Well, as long as you use US date format.... Not going to help me as I need portability.

    ReplyDelete
  4. Better:

    $date = Get-Date("2012-02-05") # For instance.....
    $startofmonth = Get-Date $date -day 1 -hour 0 -minute 0 -second 0
    $endofmonth = (($startofmonth).AddMonths(1).AddSeconds(-1))

    Gets the exact start and end of the month to the second.

    Sample output:
    PS C:\Temp> $startofmonth

    Wednesday, 1 February 2012 12:00:00 AM

    PS c:\temp> $endofmonth

    Wednesday, 29 February 2012 11:59:59 PM

    ReplyDelete
  5. # you also may use "(Get-Date)" to make this dynamic for any year for month begining 12:00:00AM to 11:59:59PM
    $currentDate = [datetime]"03/31/2008" # a Leap year example
    $currentDay = $currentDate.Day
    $PreviousMonthEndDate = Get-Date $currentDate.AddDays(-$currentDay) -Hour 11 -Minute 59 -Second 59
    $PreviousMonthStartDate = Get-Date $PreviousMonthEndDate.AddDays(-$PreviousMonthEndDate.Day +1) -Hour 12 -Minute 00 -Second 00
    $PreviousMonthEndDate
    $PreviousMonthStartDate

    ReplyDelete
  6. $endofmonth = (($startofmonth).AddMonths(1).AddMillieconds(-1))

    :)

    ReplyDelete