Reputation: 197
For Example:
IF i am running the script on the 7th and the 14th of September 2016 then my script should first find the last day of previous month which is 20160831 (Wednesday).
Now it should get me all the dates from the last day till Saturday of that week (including Saturday)
20160901 20160902 20160903
I would to store each of the dates in different variables to be used later in the script.
I have figured how to get the last day of the previous month (in the right format) but i cant figure out how to get the dates from that day till Saturday.
This script needs to be dynamic as i would like to schedule it to run every month.
Param ([system.Datetime] $date = $(get-date)) $numdays = $date.Day $lastday = $date.AddDays(-$numdays) $lastday = $date.AddDays(-$numdays).DayOfWeek
Upvotes: 0
Views: 580
Reputation: 28983
# Get the first day of this month at midnight, and step back a day to the last day of the previous month
${Date Stepper} = (Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0).AddDays(-1)
# Step forward, one day at a time, output the last day of the month until the following Saturday
$Counter = 1
Do
{
${Date Stepper} = ${Date Stepper}.AddDays(1)
Set-Item -Path "Variable:Var$Counter" -Value ${Date Stepper}.ToString("yyyyMMdd")
$Counter++
} While ([System.DayOfWeek]::Saturday -gt ${Date Stepper}.DayOfWeek)
# Test Outputs
Write-Host "Var1 = $Var1"
Write-Host "Var2 = $Var2"
Write-Host "Var3 = $Var3"
Write-Host "Var4 = $Var4"
Write-Host "Var5 = $Var5"
Write-Host "Var6 = $Var6"
Write-Host "Var7 = $Var7"
Upvotes: 2
Reputation: 7163
Adjust code like the following to meet your needs.
function Get-PreviousMonthEndToSaturday
{
[CmdletBinding()]
param (
[DateTime]
$LookbackDate
)
$retDates = @()
Write-Verbose "LookbackDate: $($LookbackDate.ToLongDateString())"
# prior month
$date = $LookbackDate.AddMonths(-1)
# all months have 28 days
$date = [DateTime]::new($date.Year, $date.Month, 28)
# while in current month...
while ($date.Month -eq $date.AddDays(1).Month)
{
$date = $date.AddDays(1)
}
# while day is not Sunday...
while ($date.DayOfWeek -ne [System.DayOfWeek]::Sunday)
{
$retDates += $date
$date = $date.AddDays(1)
}
# return desired dates
return $retDates
}
Get-PreviousMonthEndToSaturday ([DateTime]::Now) -Verbose
Get-PreviousMonthEndToSaturday ([DateTime]::Parse("2016/7/15")) -Verbose
# April ends on a Saturday
Get-PreviousMonthEndToSaturday ([DateTime]::Parse("2016/5/3")) -Verbose
Outputs:
VERBOSE: LookbackDate: Thursday, September 1, 2016
Wednesday, August 31, 2016 12:00:00 AM
Thursday, September 1, 2016 12:00:00 AM
Friday, September 2, 2016 12:00:00 AM
Saturday, September 3, 2016 12:00:00 AM
VERBOSE: LookbackDate: Friday, July 15, 2016
Thursday, June 30, 2016 12:00:00 AM
Friday, July 1, 2016 12:00:00 AM
Saturday, July 2, 2016 12:00:00 AM
VERBOSE: LookbackDate: Tuesday, May 3, 2016
Saturday, April 30, 2016 12:00:00 AM
Upvotes: 1