Link to home
Create AccountLog in
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?
Avatar of Sean
Sean
Flag of United States of America image

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

ASKER

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
Avatar of becraig
becraig
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
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.
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

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.