Created
September 13, 2012 06:33
-
-
Save mekuls/3712369 to your computer and use it in GitHub Desktop.
Powershell - Get the first and last day of the month (Australia)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$date = Get-Date | |
$numMonthsAgo = -1 | |
$firstDayOfMonth = Get-Date ((("01/" + (Get-Date $date).Month).ToString() + "/" + ((Get-Date $date).Year).ToString() + " 00:00:00")) | |
$lastDayOfMonth = (Get-Date ((("01/" + ((($firstDayOfMonth).AddMonths(1)).Month).ToString() + "/" + ((($firstDayOfMonth).AddMonths(1)).Year).ToString())))) - (New-TimeSpan -seconds 1) | |
$firstDayOfMonth = $firstDayOfMonth.AddMonths($numMonthsAgo) | |
$lastDayOfMonth = $lastDayOfMonth.AddMonths($numMonthsAgo) | |
Write-Host ("-StartDate " + (Get-Date $firstDayOfMonth -format d) + " -EndDate " + (Get-Date $lastDayOfMonth -format d)) | |
# Find my folder that contains a file that I created n months ago | |
$items = Get-ChildItem "C:\users\skycoder" -Recurse | Where { $_.CreationTime -igt $firstDayOfMonth -and $_.CreationTime -ilt $lastDayOfMonth -and $_.PSIsContainer } | | |
Select FullName, PSParentPath | Write-Host |
@MRQ - Thanks
Function parm defaults to current date. Function returns a date array with:
Date Supplied
First Day of Month
Last Day of Month
Function GetFirstLastDayOfMonth (
$aDateSet=@($aDate)
$firstDay = Get-Date $aDate -day 1 -hour 0 -minute 0 -second 0
$lastDay = (($firstDay).AddMonths(1).AddSeconds(-1))
$aDateSet+=$firstDay
$aDateSet+=$lastDay
Return $aDateSet
}
Allows calls like below:
$x = GetFirstLastDayOfMonth # JULY 22, 2014
$x[1] # first day of current month
$x[2] # last day of current month
$x[0] # date supplied for computation
Tuesday, July 22, 2014 2:09:21 PM
Tuesday, July 01, 2014 12:00:00 AM
Thursday, July 31, 2014 11:59:59 PM
$y[0]
$y[1]
$y[2]
Tuesday, April 22, 2014 2:10:11 PM
Tuesday, April 01, 2014 12:00:00 AM
Wednesday, April 30, 2014 11:59:59 PM
Might need some error check if .typeOf is not a date on supplied parameter
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're better off making it date format agnostic. If you have a date in $date:
$startofmonth = Get-Date $date -day 1 -hour 0 -minute 0 -second 0
$endofmonth = (($startofmonth).AddMonths(1).AddSeconds(-1))
This will result in this (I had a date in Feb 2016 in there for testing):
PS C:\Temp> $startofmonth
Wednesday, 1 February 2016 12:00:00 AM
PS C:\temp> $endofmonth
Wednesday, 29 February 2016 11:59:59 PM