Avatar of -TNT-
-TNT- asked on

PowerShell Run if Day and Hour

I am trying to write a PowerShell script to run a segment of code if the day and hour match:

if it is Monday 10am hour run:

if it is Monday 6pm hour run:

If it is Sunday 7pm hour run:

etc.

I have found several bulky ways of doing this but I am trying to keep things tight. Any ideas?
Powershell

Avatar of undefined
Last Comment
Qlemo

8/22/2022 - Mon
Sean

why not do a scheduled task to run the script at those times?
ASKER
-TNT-

Because there are a total of about 12 tasks that need to be run and on several computers. So to schedule 12 tasks on 5 computers will take a long time, plus if we replace a computer we have to do it all over again.
ASKER CERTIFIED SOLUTION
becraig

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Sean

what you can do is get-date -format ddd to get the day of the week and get-date -format hh:mm to get the time. Then you can do an if statement to check those to run your script and then put everything in large loop with a sleep timer.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
footech

Here's another method.  Just substitute your action for "First", "Second", etc.
switch (Get-Date)
{
    {$_.dayofweek -eq "Monday" -and $_.Hour -eq 10}
        { "First"}
    {$_.dayofweek -eq "Monday" -and $_.Hour -eq 18}
        { "Second" }
    {$_.dayofweek -eq "Sunday" -and $_.Hour -eq 19}
        { "Third" }
}

Open in new window

Qlemo

Are the tasks the same for all machines? If so, running a PS script on one "server" doing the task scheduling might be a better approach. Or let that single machine run 12 tasks, each performing the same action for a list of machines.