Modifying a Date variable in PowerShell - powershell

I'm looking to create a schedule type check.
I want to check today's date and if it's not the correct Day of the week for a task to run it continues.
Once the day is correct, I will then create a timer based on the difference between the expected execution time (let's say 01:00) and now. I have had a few ideas on how to achieve this, one of them being below. The problem I am facing is I am unsure of how to create a CountDown timer from the NEW-TIMESPAN output and how to dynamically change the $EndDate time value to meet the relevant schedule value. Any pointers would be appreciated.
$date = Get-Date -DisplayHint Date
if ($date.DayOfWeek -eq 'Friday')
{
$StartDate = (GET-DATE)
# I am unsure of how to dynamically change the $EndDate variable time value and create the 'CountDown variable' from the New-TimSpan output.
$EndDate = [datetime]"11/13/2020 01:00"
$countdown = NEW-TIMESPAN -Start $StartDate -End $EndDate
}
Write-Host $date
EDIT
With some help from #AdminOfTHings I have come up with the following solution.
if ($date.DayOfWeek -eq $schedule.Day)
{
$StartDate = (GET-DATE)
$tempDate = (GET-DATE).ToString()
$tempDate, $tempTime = $tempDate.Split(' ')
[datetime]$DateTime = $tempDate + " $($schedule.Time)"
$Timer = NEW-TIMESPAN -End $DateTime
$CountDown = $Timer.TotalSeconds
while ($CountDown -gt 0)
{
sleep 1
$CountDown--
}
else
{
#START SERVICE
}
}

New-Timespancreates a TimeSpan object regardless of the parameter set being used. If you know how long a timespan should be, then you can statically create that combination of days, hours, minutes, and seconds, making end time irrelevant.
$date = Get-Date -DisplayHint Date
if ($date.DayOfWeek -eq 'Friday') {
$countdown = New-Timespan -Hours 8
}
You could have a situation where you know you want the task to span 2 days but want it to end at 01:00. This would make the total time variable. You can make adjustments based on start time:
$date = Get-Date -DisplayHint Date
if ($date.DayOfWeek -eq 'Friday') {
$end = Get-Date -Day $date.AddDays(2).Day -Month $date.AddDays(2).Month -Hour 1 -Minute 0 -Second 0
$countdown = New-TimeSpan -End $end
}
Edit:
If you reach a target day of week and want to create a timer that lasts until the next 01:00 hour from that point in time, you can do the following:
$date = Get-Date
if ($date.DayOfWeek -eq 'Friday') {
if ($date.Hour -lt 1) {
# dynamic end date - start date
$countdown = (Get-Date $date -Hour 1 -Minute 0 -Second 0) - $date
} else {
# dynamic end date - start date
$countdown = (Get-Date $date.AddDays(1) -Hour 1 -Minute 0 -Second 0) - $date
}
}
$countdown.TotalSeconds # total seconds of the time span
As an aside, if you expect the starting time to be now, you can skip the -Start parameter. Leaving off -Start assumes the starting time is now.

Thanks for the help, I have no idea why I didn't think of it before but I have come up with
if ($date.DayOfWeek -eq 'Friday')
{
$StartDate = (GET-DATE)
$tempDate = (GET-DATE).ToString()
$tempDate, $tmpTime = $tempDate.Split(' ')
datetime]$DateTime = $tempDate + " $($schedule.Time)"
$Timer = NEW-TIMESPAN -End $DateTime
}
Just need to understand how to use the timer now (all in seconds)

Related

Powershell how to check if friday is the last day of the month , returning True from a Function

I have tried to make a function in Powershell that produces a True if the last day of the month is friday.
function Get-LastFridayOfMonth([DateTime] $d) {
$lastDay = new-object DateTime($d.Year, $d.Month,[DateTime]::DaysInMonth($d.Year, $d.Month))
$diff = ([int] [DayOfWeek]::Friday) - ([int] $lastDay.DayOfWeek)
if ($diff -gT 0) {
return $lastDay.AddDays(- (7-$diff))
} else {
return $lastDay.AddDays($diff)
}
}
$testdate = Get-LastFridayOfMonth (Get-Date)
But how to check if that friday is the last day of the month ?
#Theo's answer reframes your question and gives a nice all-in-one solution, but to address your specific question:
"how to check if [a date] is the last day of the month ?"
you can just add one day to the date and see if the month changes. If it does change then the original date must be the last one in the month…
$testdate = [datetime] "2023-01-31"
$isLastDayOfMonth = $testdate.AddDays(1).Month -ne $testdate.Month
$isLastDayOfMonth
# True
$testdate = [datetime] "2023-01-30"
$isLastDayOfMonth = $testdate.AddDays(1).Month -ne $testdate.Month
$isLastDayOfMonth
# False
$testdate = Get-LastFridayOfMonth (Get-Date)
$isLastDayOfMonth = $testdate.AddDays(1).Month -ne $testdate.Month
$isLastDayOfMonth
# depends on if the month ends on a friday
I would change that function to just return the last days weekday so after calling it you can decide what weekday you get for the given date.
function Get-LastWeekDayOfMonth {
param (
[datetime]$Date = (Get-Date)
)
# .AddDays(-$Date.Day+1) sets the given date to the 1st of that month
$Date.AddDays(-$Date.Day+1).AddMonths(1).AddDays(-1).DayOfWeek
}
switch (Get-LastWeekDayOfMonth) {
'Friday' { "It's a Friday !" }
default { $_ }
}
Using the current date (February 2023) it would yield Tuesday
If you specify for instance March 2023
$d = Get-Date -Year 2023 -Month 3 -Day 1
switch (Get-LastWeekDayOfMonth -Date $d) {
'Friday' { "It's a Friday !" }
default { $_ }
}
The outcome will be It's a Friday !
If however you want a function to simply return $true or $false when the month end in a Friday or not, do this instead:
function Test-LastDayOfMonthIsFriday {
param (
[datetime]$Date = (Get-Date)
)
# .AddDays(-$Date.Day+1) sets the given date to the 1st of that month
$Date.AddDays(-$Date.Day+1).AddMonths(1).AddDays(-1).DayOfWeek -eq 'Friday'
}
Test-LastDayOfMonthIsFriday # --> $false
Test-LastDayOfMonthIsFriday -Date (Get-Date -Year 2023 -Month 3 -Day 1) # --> $true
Special thanks to mklement0 for the $Date.AddDays(-$Date.Day+1) part which always sets the date to the first day of that month

Testing if now if between two times that span midnight

I've tried searching for this, but I'm at a loss... I can find answers for other languages, but not for PowerShell.
Basically, I want to test if the time now is between 21:15 and 5:45.
I'm pretty sure I need to use New-TimeSpan - but, for the life of me, I just can't work it out.
I'd share my test code, but I think I'm so far away from the answer that it wouldn't be of any help.
Can anyone help me?
Use Get-Date to create DateTime objects describing those thresholds as points in time on todays date, then test if the time right now is before the early one or after the late one:
$now = Get-Date
$morning = Get-Date -Date $now -Hour 5 -Minute 45
$evening = Get-Date -Date $now -Hour 21 -Minute 15
$isWithinRange = $now -le $morning -or $now -ge $evening
If this is purely about the time of day and you don't need any date calculations, you can do the following, relying on the fact that for padded number strings lexical sorting equals numeric sorting:
# Get the current point in time's time of day in 24-hour ('HH') format.
# Same as: [datetime]::Now.ToString('HH\:mm')
$timeNow = Get-Date -Format 'HH\:mm'
$timeNow -ge '21:15' -or $timeNow -le '05:45'
If you'd have to check if you are in the range 23:00-04:00, crossing the midnight, you could:
$now=(Get-Date).TimeofDay
if ($now.TotalHours -ge 23 -or $now.TotalHours -lt 04)
{"In Range"}
else
{"Out of range"}

PowerShell returns 2 as week number on January 06 2020

A quick question, apparently today (January 06, 2020) week number should be 2, because there are 53 weeks in 2020.
However, the following PowerShell snippet returns 1:
(Get-Date -UFormat %V)
What is the good approach getting the week number properly?
To translate this Get the correct week number of a given date C# answer from #il_guru into PowerShell:
Function GetIso8601WeekOfYear([DateTime]$Date) {
$Day = (Get-Culture).Calendar.GetDayOfWeek($Date)
if ($Day -ge [DayOfWeek]::Monday -and $Day -le [DayOfWeek]::Wednesday) {$Date = $Date.AddDays(3)}
(Get-Culture).Calendar.GetWeekOfYear($Date, 'FirstFourDayWeek', 'Monday')
}
GetIso8601WeekOfYear (Get-Date)
2
GetIso8601WeekOfYear (Get-Date('2016-01-01'))
53
You could detect a leap year and then adjust the week number based off the result.
if(((Get-Date).year)%4 -eq 0){
$week = (Get-Date -UFormat %V) -as [int]
$week++
}else{
$week = (Get-Date -UFormat %V)
}
Write-Host $week

Date variable still contains todays date after assigning it the value of upcoming Friday

I have a little powershell script to find the date of the upcoming Friday. However after assigning the value of the Friday date, my date variable still prints out todays date.
$date = Get-Date
for($i=1; $i -le 7; $i++)
{
if($date.AddDays($i).DayOfWeek -eq 'Friday')
{
$date.AddDays($i)
break
}
}
Write-Host "$date"
AddDays seems to return new date object and not update the date object in $date. Try assigning $date to the new date inside the if statement as follows:
$date = $date.AddDays($i)
$date = Get-Date
for($i=1; $i -le 7; $i++)
{
if($date.AddDays($i).DayOfWeek -eq 'Friday')
{
$date = $date.AddDays($i)
break
}
}
Write-Host "$date"
You have to return the value you're assigning to $date back to itself.
You probably tested it yesterday (Wednesday) because it works today.
The problem in your code is that it reuses the same $Date each time and probably step over the expected date:
Date + 1
Date + 3 (1 + 2)
Date + 6 (1 + 2 + 3)
...
In other words, the $date = Get-Date should be in your loop.
(Get-Date).AddDays((1..7 | Where {(Get-Date).AddDays($_).DayOfWeek -eq 'Friday'}))

Date Time day of the week comparison logic in PowerShell

Date Time objects allow us to perform actions like this:
$CurrentDate = Get-Date
$TextDate = get-date -date "02/10/2016"
if ($TextDate -lt $CurrentDate){
Write-Host "True"
}
else {
Write-Host "False"
}
This outputs "True" because $TextDate is less than $CurrentDate.
Following the same logic, why does the following code output false?
$CurrentDate = Get-Date -UFormat %V
$TextDate = Get-Date -date "02/10/2016"
$TextDate = Get-Date -date $TextDate -UFormat %V
if ($TextDate -lt $CurrentDate){
Write-Host "True"
}
else {
Write-Host "False"
}
The only difference is that we are comparing the week of the year. If you change the comparison to -gt, the code returns True.
Formatted dates are strings, not integers. The string "6" is after the string "11".
This would be the most correct way to do this:
First, decide what the "first week of the year" actually means:
$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstDay;
#$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFourDayWeek;
#$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFullWeek;
Then, decide which day of the week is the first day of the week:
$FirstDayOfWeek = [System.DayOfWeek]::Sunday;
#$FirstDayOfWeek = [System.DayOfWeek]::Monday;
#Any day is available
Then you can get your correct week number:
$Today = (Get-Date).Date;
$TodayWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($Today, $CalendarWeekRule, $FirstDayOfWeek);
$TargetDate = Get-Date -Date "2016-02-10";
$TargetWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($TargetDate, $CalendarWeekRule, $FirstDayOfWeek);
if ($TargetWeek -lt $TodayWeek) { $true } else { $false }
Note that if you want a full ISO 8601 week, it's somewhat more complicated.
Because you are comparing string-objects.
(Get-Date -UFormat %V).GetType().FullName
System.String
When comparing strings using -gt and -lt it sorts the strings and because 6 comes after 1, your 6 -lt 11-test returns false.
Both $TextDate and $CurrentDate are of type [string] so what you are evaluating is '6' -lt '11' which will return false. Operators are based on the left side type in PowerShell. So in order to force an integer comparison modify your expression as under
if ([int]$TextDate -lt $CurrentDate)
{
Write-Host "True"
}
else
{
Write-Host "False"
}