Powershell v3 comes with all these new job-scheduling cmdlets. They look great, but I'm having trouble creating a specific trigger. I need to run a job daily, repeating itself every hour, for a specific interval.
Using the Task-Scheduler UI is straightforward, but I can't find my way around the New-JobTrigger cmdlet.
If I use the Daily parameter-set, I don't have the Repetition option:
New-JobTrigger [-Daily] -At <DateTime> [-DaysInterval <Int32> ] [-RandomDelay <TimeSpan> ] [ <CommonParameters>]
If I use the Once parameter-set, I can't have the Daily option
New-JobTrigger [-Once] -At <DateTime> [-RandomDelay <TimeSpan> ] [-RepetitionDuration <TimeSpan> ] [-RepetitionInterval <TimeSpan> ] [ <CommonParameters>]
What I need, but obviously doesn't work, is a mix between the two. For example:
New-JobTrigger -Daily -At xxxx -RepetitionDuration (New-TimeSpan -Hours 5) -RepetitionInterval (New-TimeSpan -Hours 1)
Is it possible? Maybe mixing several triggers for the same job?
This works for me:
Note - I know that the original question was related to New-JobTrigger
The intent was to provide a possible solution that may be translatable
to New-JobTrigger as well given the issue applies to both.
$A = New-ScheduledTaskAction -execute "powershell" -argument "-nologo -noprofile -noninteractive C:\MyScript.ps1"
$T = New-ScheduledTaskTrigger -Once -At 03:00AM
Register-ScheduledTask -TaskName StartBasicServices_Local -Trigger $T -Action $A -description "MyScript" -User "NT AUTHORITY\SYSTEM" -RunLevel 1
$T.RepetitionInterval = (New-TimeSpan -Minutes 5)
$T.RepetitionDuration = (New-TimeSpan -Days 1)
Set-ScheduledTask StartBasicServices_Local -Trigger $T
I have been working on this issue all day and i finally have the answer. You cant. Not using those cmdlets anyway. At first i thought this might work as a workaround:
$Job = Register-ScheduledJob -Name "YourJobName" {Gci};
$RepeatTrigger = New-JobTrigger -Once -At (Get-Date 10:00).ToShortTimeString() - RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration (New-TimeSpan -Hours 7);
$RepeatTrigger.Frequency = [Microsoft.PowerShell.ScheduledJob.TriggerFrequency]::Daily;
Add-JobTrigger -InputObject $Job -Trigger $RepeatTrigger
However, it doesnt. Using trace-command it looks like it validates the attributes depending on the parameter set. The same is true when using schtasks:
schtasks /create /tn YourTask /tr notepad.exe /sc Hourly
It will create it hourly but again it will have to be a once off task. By the looks of things there is a .Net wrapper for the for the COM API which is probably going to be your best bet if your new to PoSH. You can find it on CodePlex.
I know about Add-JobTrigger, but I don't understand how to achieve my
specific requirement: run a job daily, repeating itself every hour,
for a specific duration. For example: every day, at 10 AM, repeating
every 1 hour until 5 PM. – scarmuega Oct 7 '12 at 18:14
Create the job with Register-ScheduledJob.
Then add the daily triggers.
It would be great if we could do this, but the -Daily doesn't work in PowerShell 4.0.
Read on, I have an alternative for you.
# Technet: http://technet.microsoft.com/en-us/library/hh849759.aspx
# To create a repeating schedule, use the Once parameter with the RepetitionDuration and RepetitionInterval parameters.
# -RepetitionInterval Repeats the job at the specified time interval. For example, if the value of this parameter is 2 hours, the job is triggered every two hours.
# The default value, 0, does not repeat the job.
# -RepetitionDuration Repeats the job until the specified time expires. The repetition frequency is determined by the value of the RepetitionInterval parameter.
# For example, if the value of RepetitionInterval is 5 minutes and the value of RepetitionDuration is 2 hours, the job is triggered every five minutes for two hours.
#
$trigger = New-JobTrigger -Daily -At 10:00 -RepetitionDuration 7:00:00 -RepetitionInterval 1:00:00 -DaysofWeek
Register-ScheduledJob -Name Test -Trigger $trigger -ScriptBlock {}
You can just organize your job so that it has a trigger for each hour that you want.
$trigger4am = New-JobTrigger -Daily -At 04:10
Register-ScheduledJob -Name ArchiveProd -Trigger $trigger4am -ScriptBlock {E:\ArchiveProd.ps1}
$trigger8am = New-JobTrigger -Daily -At 08:10
$trigger12pm = New-JobTrigger -Daily -At 12:10
$trigger6pm = New-JobTrigger -Daily -At 18:10
Add-JobTrigger -Trigger $trigger8am -Name ArchiveProd
Add-JobTrigger -Trigger $trigger12pm -Name ArchiveProd
Add-JobTrigger -Trigger $trigger6pm -Name ArchiveProd
Hope that is what you needed. It works nice for my situation, although I would prefer to just add the Daily parameter. Maybe someobody can improve on this for me?
A late answer, but I started with this question then searched more and found a solution at this link, Petri.com
$principal = New-ScheduledTaskPrincipal -UserID MyDomain\MyGMSA$ -LogonType Password -RunLevel Highest
$action = New-ScheduledTaskAction "E:\DoSomething"
$when = New-ScheduledTaskTrigger -Daily -At "00:02" -DaysInterval 1
Register-ScheduledTask -TaskName MyNewTask–Action $action –Principal $principal -Trigger $when
$t = Get-ScheduledTask -TaskName MyNewTask
$t.Triggers.repetition.Interval = "PT15M" #every 15 mins
$t.Triggers.repetition.Duration = "PT7H30M" #for 7 hours 30
$t | Set-ScheduledTask
Try using Add-JobTrigger to add multiple job triggers to a scheduled job.
clear
Import-Module TaskScheduler
# Create a new task
$task = New-Task
Add-TaskAction -Task $task -Path "C:\Windows\notepad.exe"
Add-TaskTrigger -Task $task -Daily -At "06:00" -Repeat "05:00" -For "12:00"
# Register the task
Register-ScheduledTask -Name "PowerShell - MyScript.ps1" -Task $task
Get-ScheduledTask PowerShell* | select -Property Name
# Remove-Task -n Power*
You can create multiple triggers, see below:
$job = Register-ScheduledJob -Name "Test1" -FilePath "C:\temp\script.ps1"
$triggers = New-Object System.Collections.Generic.List[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]
$times = ("08:00", "09:00", "10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "19:00", "22:00")
foreach($t in $times){
$triggers.Add((New-JobTrigger -Daily -At $t))
}
$job.AddTriggers($triggers, $true)
Or easier (but slower)
$MyJob = Register-ScheduledJob -Name "MyJob" -FilePath "C:\temp\test.ps1"
$times = ("08:00", "09:00", "10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "19:00", "22:00")
foreach($t in $times){$MyJob | Add-JobTrigger -trigger (New-JobTrigger -Daily -At $t)}
When you are creating a Scheduled-Job with "Register-ScheduledJob", you can't configure a daily execution in combination with a repetition interval. Even if you modify the properties "RepetitionInterval" and "RepetitionDuration" of the ScheduledJobTrigger object manually, the trigger will be configured to execute daily OR once with the repetition.
I managed to configure it by obtaining the corresponding task for the job through the Get-ScheduledTask method and modifying the trigger there:
$trigger = New-JobTrigger -Weekly -WeeksInterval 1 -At "06:00" -DaysOfWeek Monday,Tuesday,Wednesday,Thursday,Friday
Register-ScheduledJob -Name $cronjobName -Trigger $trigger -ScriptBlock $scriptBlock
$task = Get-ScheduledTask -TaskName $cronjobName
$trigger = $task.Triggers
$trigger.Repetition.Interval = "PT10M"
$trigger.Repetition.Duration = "PT12H"
Set-ScheduledTask -TaskPath $task.TaskPath -TaskName $cronjobName -Trigger $trigger
Related
I cant seem to figure out how to create a new scheduled task that is triggered daily and repeats every 30 minutes. I have been going in circles.
Everything about this below works for setting the task I want, but only triggered once.
#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"
#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"
####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden `"$psscript `'$sourcedir`' `'$destdir`' `'$archivepassword`'`""
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask EncryptSyncTEST -InputObject $ST -User $username -Password $password
If I change -Once to -Daily I lose the -RepetitionInterval flags. And if I come back to update the task to daily after registering it, it wipes the repeating trigger.
This isn't an uncommon scheduling method, and is easily applied through the task scheduler UI. I feel like it is probably simple but I am missing it.
Any help is appreciated.
EDIT: Addressing the duplicate question. The question in the post "Powershell v3 New-JobTrigger daily with repetition" is asking the same. But as I commented earlier, none of the answers solve the issue. The marked answer does exactly what I already have here, it sets a task with a -Once trigger, then updates it to repeat every 5 minutes for 1 day. After the first day that task will never be triggered again. It does not address the issue of triggering a task everyday with repetition and duration until the next trigger.
The other three answers on that post are also not addressing the question. I do not know why it was marked answered, because it is not correct. I fully explored those replies before I posted this question. With that post having aged and being marked as answered I created this question.
Note: I have found a workaround, but not a great one. At current it seems the easiest way to define custom triggers using powershell is to manipulate the Scheduled Task XML and import it directly using Register-ScheduledTask
While the PowerShell interface for scheduled task triggers is limited, it turns out if you set the RepetitionDuration to [System.TimeSpan]::MaxValue, it results in a duration of "Indefinitely".
$trigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 5) `
-RepetitionDuration ([System.TimeSpan]::MaxValue)
Tested on Windows Server 2012 R2 (PowerShell 4.0)
Here is a way of creating a scheduled task in Powershell (v5 on my machine, YMMV) that will start at 12AM every day, and repeat hourly for the rest of the day. Therefore it will run indefinitely. I believe this is a superior approach vs setting -RepetitionDuration to ([timespan]::MaxValue) as I commented earlier, as the trigger will show up in the Task Scheduler as:
At 12:00 AM every day - After triggered, repeat every 30 minutes for a duration of 1 day.
Rather than the date on which the task was registered appearing in the trigger as approaches that use -Once -At 12am result in, create the trigger as a simple -Daily -At 12am, register the task then access some further properties on the tasks Triggers property;
$action = New-ScheduledTaskAction -Execute <YOUR ACTION HERE>
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -TaskName "MyTask" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" //Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT30M" //Repeat every 30 minutes, use PT1H for every hour
$task | Set-ScheduledTask
//At this point the Task Scheduler will have the desirable description of the trigger.
Create base trigger:
$t1 = New-ScheduledTaskTrigger -Daily -At 01:00
Create secondary trigger (omit -RepetitionDuration for an indefinite duration):
$t2 = New-ScheduledTaskTrigger -Once -At 01:00 `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)
Take repetition object from secondary, and insert it into base trigger:
$t1.Repetition = $t2.Repetition
Bob's your uncle:
New-ScheduledTask -Trigger $t1 -Action ...
I'm sure there must be a better way, but this is my current workaround.
I created a task with the triggers I wanted then grabbed the XML it generated.
Below I am creating the task, then pulling the XML for that new task, replacing my triggers, then un-registering the task it and re-registering it with the updated XML.
Long term, I will probably just use the full XML file for the task and replace the strings as needed, but this works for now.
#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"
#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"
####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden '$EncryptSync' '$sourcedir' '$destdir' '$archivepassword'"
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask "EncryptSyncTEST" -InputObject $ST -User $username -Password $password
[xml]$EncryptSyncST = Export-ScheduledTask "EncryptSyncTEST"
$UpdatedXML = [xml]'<CalendarTrigger xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Repetition><Interval>PT30M</Interval><Duration>P1D</Duration><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2013-11-18T07:07:15</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>'
$EncryptSyncST.Task.Triggers.InnerXml = $UpdatedXML.InnerXML
Unregister-ScheduledTask "EncryptSyncTEST" -Confirm:$false
Register-ScheduledTask "EncryptSyncTEST" -Xml $EncryptSyncST.OuterXml -User $username -Password $password
The easiest method I found to accomplish this is to use schtasks.exe. See full documentation at https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx
schtasks.exe /CREATE /SC DAILY /MO 1 /TN 'task name' /TR 'powershell.exe C:\test.ps1' /ST 07:00 /RI 30 /DU 24:00
This creates a task that runs daily, repeats every 30 minutes, for a duration of 1 day.
https://stackoverflow.com/a/54674840/9673214
#SteinIP solution worked for me with slight modification
In 'create secondary trigger' part added '-At' parameter with same value as in 'create base trigger' part.
Create base trigger
$t1 = New-ScheduledTaskTrigger -Daily -At 01:00
Create secondary trigger:
$t2 = New-ScheduledTaskTrigger -Once -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55) -At 01:00
Do the magic:
$t1.Repetition = $t2.Repetition
New-ScheduledTask -Trigger $t1 -Action ...
Another way to do it is just to create multiple triggers like so:
$startTimes = #("12:30am","6am","9am","12pm","3pm","6pm")
$triggers = #()
foreach ( $startTime in $startTimes )
{
$trigger = New-ScheduledTaskTrigger -Daily -At $startTime -RandomDelay (New-TimeSpan -Minutes $jitter)
$triggers += $trigger
}
If you wanna a infinate Task duration on Windows 10 just use this (Do not specify -RepetitionDuration)
$action = New-ScheduledTaskAction -Execute (Resolve-Path '.\main.exe')
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "GettingDataFromDB" -Description "Dump of new data every hour"
Here's another variation that seems to work well for this old chestnut, but is less complex than some of the other solutions. It has been tested on Server 2012 R2, Server 2016 and Server 2019, with the default PS version on each OS. "Merging" the triggers didn't work for me on 2012. Didn't bother with the others.
The steps are simple:
Create the scheduled task with the basic schedule first
Extract the details from the new task
Modify the trigger repetition/duration
Update the existing task with the modified version
The example consists of a daily task that repeats every hour for a day (I've set it to 23 hours to make the date/time syntax a little clearer). The same timespan format is used for Duration and Interval.
# create the basic task trigger and scheduled task
$trigger = New-ScheduledTaskTrigger -Daily -At 15:55
$Settings = New-ScheduledTaskSettingsSet –StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -Setting $Settings -User $User
# Get the registered task parameters
$task = Get-Scheduledtask $TaskName
# Update the trigger parameters to the repetition intervals
$task.Triggers[0].Repetition.Duration = "P0DT23H0M0S"
$task.Triggers[0].Repetition.Interval = "P0DT1H0M0S"
# Commit the changes to the existing task
Set-ScheduledTask $task
Note that if your task has multiple triggers - although that'd be unusual if you have a repetition interval - you need to modify whichever trigger needs the repetitions. The example only has a single trigger, so we just select the first (and only) member of the list of triggers - $task.Triggers[0]
The timespan is ISO 8601 format - it's a string with no spaces. The required numeric value precedes the time designation (e.g. 1H for one hour, not H1). The string must contain all the time designations as listed, with a 0 substituting for any empty values. The P ("period") at the beginning indicates it's a duration rather than a timestamp.
P(eriod)0D(ays)T(ime)0H(ours)0M(inutes)0S(econds)
P0DT1H0M0S = 0 days, 1 hours, 0 minutes, 0 seconds
P0DT0H15M30S = 0 days, 0 hours, 15 minutes, 30 seconds
You can use a similar method to modify the trigger if you want to change a start time on a task. This applies to -Once or -Daily tasks.
$task = Get-ScheduledTask $taskname
$d = ([DateTime]::now).tostring("s") # 2021-11-30T17:39:31
$task.Triggers[0].StartBoundary = $d
Set-ScheduledTask $task
Old question and I'm not sure if the powershell cmdlets are a requirement. But I just use schtasks.
If you want to run every 15 minutes:
schtasks /f /create /tn taskname `
/tr "powershell c:\job.ps1" /ru system `
/sc minute /mo 15 /sd 01/01/2001 /st 00:00
This will 'trigger' on 1/1/2001 midnight and run every 15 minutes. so if you create it today, it'll just run on the next event interval.
If you want it to 'trigger' every single day, you can do this:
schtasks /f /create /tn taskname `
/tr "powershell c:\job.ps1" /ru system `
/sc daily /sd 01/01/2001 /st 10:00 /du 12:14 /ri 15
This will 'trigger' on 1/1/2001 10am, and run every 15 minutes for 12 hours and 14 minutes. so if you start it today, it'll just run on the next event interval.
I normally run my 'every 15 minutes' like the top one and my 'every day for x times' like the bottom. So if i need to run something at say 10am and 2pm, i just change the /du on the second one to 5 hours and the /ri to 4. then it repeates every 4 hours, but only for 5 hours. Technically you may be able to put it at 4:01 for duration, but i generally give it an hour to be safe.
I used to use the task.xml method and was having a really tough time with the second scenario until I noticed in a task.xml that was exported it basically just has something like this below.
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT3H</Interval>
<Duration>PT15H</Duration>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2017-11-27T05:45:00</StartBoundary>
<ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
This was for a job that ran every 3 hours between 5:45 and 7:45. So I just fed the interval and duration into a daily schedule command and it worked fine. I just use an old date for standardization. I'm guessing you could always start it today and then it would work the same.
To run this on remote servers I use something like this:
$sb = { param($p); schtasks /f /create /tn `"$p`" /tr `"powershell c:\jobs\$p\job.ps1`" /ru system /sc daily /sd 01/01/2001 /st 06:00 /du 10:00 /ri (8*60) } }
Invoke-Command -ComputerName "server1" -ScriptBlock $sb -ArgumentList "job1"
Working in Windows 10
Set-ExecutionPolicy RemoteSigned
$action=New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'C:\Users\hp\Anaconda3\python.exe C:\Users\hp\Desktop\py.py'
$trigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepetitionDuration (New-TimeSpan -Days (365 * 20))
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ts2" -Description "tsspeech2"
I am trying to create a task scheduler like below
So far I came up with below code.
#Variables
$TaskName = "TestingTask"
$username ="user"
$password ='password'
$description = "This is a testing task"
#Create Scheduled Task
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "E:\script.ps1"
$Trigger = New-ScheduledTaskTrigger -At 10AM -Weekly -WeeksInterval 2 -DaysOfWeek Friday
$taskPrincipal = New-ScheduledTaskPrincipal -UserId 'user' -RunLevel Highest
$ScheduledTask = New-ScheduledTask -Action $action -Trigger $trigger -Description $description -Principal $taskPrincipal
Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User $username -Password $password
Please let me know how can we schedule monthly like this.
From the help for the cmdlet Get-Help New-ScheduledTaskTrigger -full
Example 4: Register a scheduled task that starts every-other week
PS C:\>$Sta = New-ScheduledTaskAction -Execute "Cmd"
The second command creates a scheduled task trigger that starts every other Sunday at 3:00 A.M and assigns the ScheduledTaskTrigger object to the $Stt variable.
PS C:\>$Stt = New-ScheduledTaskTrigger -Weekly -WeeksInterval 2 -DaysOfWeek Sunday -At 3am
The third command registers the scheduled task Task01 to run the task action named Cmd every other Sunday at 3:00 A.M.
PS C:\>Register-ScheduledTask Task01 -Action $Sta -Settings $Stt
This example registers a scheduled task that starts every other week.
The first command creates a scheduled task action named Cmd and assigns the ScheduledTaskAction object to the $Sta variable.
I would assume that if you set -Weekly -WeeksInterval 4 should set the task to run once every 4 weeks, and should essentially make it a month. But you are right, there is no real option to identify a "month", you should try this out and see how it looks like the GUI.
Another thing to try is, to make a montly based task in the GUI and use Get-ScheduledTask to see how the interval is configured.
I want to set the value for the option "Stop task if runs longer than" in the windows schedule task Trigger tab using Powershell.
Already tried with /DU switch but it is not working.
Below is the screenshot for the same.
let me know in case of any further information is required.
#TobyU: I tried your suggestion as well but it is not setting up the required value. Below is the screenshot for your reference.
Thank you in advance.
I'm using Windows 10 Pro and PowerShell 7 and the following works well for me.
Creating a new task:
# Creating a task with multiple triggers and different execution limits
$taskName = "MyTask"
$trigger1 = New-ScheduledTaskTrigger -Once -At "2021-05-10 12:00:00"
$trigger1.ExecutionTimeLimit = "PT20M"
$trigger2 = New-ScheduledTaskTrigger -Once -At "2021-05-13 17:30:30"
$trigger2.ExecutionTimeLimit = "PT50M"
$taskTriggers = #(
$trigger1,
$trigger2
)
$taskAction = New-ScheduledTaskAction -Execute "notepad.exe"
Register-ScheduledTask -TaskName $taskName -Trigger $taskTriggers -Action $taskAction
For updating the trigger of an existing task the solution proposed by #TobyU worked well for me:
# Updating execution limits of a task that already exists
$taskName = "MyTask"
$task = Get-ScheduledTask -TaskName $taskName
$task.Settings.ExecutionTimeLimit = "PT30S" # Global limit
$task.Triggers[0].ExecutionTimeLimit = "PT10S" # Limit for trigger 1
$task.Triggers[1].ExecutionTimeLimit = "PT15S" # Limit for trigger 2
Set-ScheduledTask $task
However, you can also completely replace the old trigger with a new one:
# Completely replacing all triggers with new one of an already existing task
$taskName = "MyTask"
$trigger = New-ScheduledTaskTrigger -Once -At "2021-05-17 17:17:17"
$trigger.ExecutionTimeLimit = "PT42M"
Set-ScheduledTask -TaskName $taskName -Trigger $trigger
You can set it for the whole task at once:
$task = Get-ScheduledTask -TaskName "MyTask"
$task.Settings.ExecutionTimeLimit = "PT3H"
Set-ScheduledTask $task
Stops after 3 hours in the above example.
This is how you set it only for a specific trigger:
$task = Get-ScheduledTask -TaskName "MyTask"
$task.Triggers[0].ExecutionTimeLimit = "PT3H"
Set-ScheduledTask $task
Where Triggers[0] is the specific trigger you want to adjust since $task.Triggers returns an array with all the available trigger objects for the specific task.
Create Schedule Task Remotely
Invoke-Command -ComputerName Computername -Scriptblock
{
$action = New-ScheduledTaskAction -Execute 'C:\app.exe” '
$trigger = New-ScheduledTaskTrigger -Daily -At 10am -RandomDelay (New-TimeSpan - Minutes 480)
$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -
RunLevel Highest
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -
TaskName "Schedule_task_name" -Description "Task Description"
$Task = Get-ScheduledTask -TaskName "Schedule_task_name"
$Task.Triggers[0].ExecutionTimeLimit= "PT30M"
Set-ScheduledTask $Task
}
Looks like your format for the ExecutionTimeLimit may need tweaking. In my case, I wanted the setting removed (ie the tickbox unticked). I couldn't figure this out, but using the following format for ExecutionTimeLimit did work, so I could set it to a far away value: d.hh:mm:ss, ie 1000 days:
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit 1000.00:00:00
Register-ScheduledTask -TaskName 'name' -Action $action -Trigger $trigger -Settings $settings
I need to write a script, which will create task scheduler job, which at pc startup will run executable. In short, script will be something like this:
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:10
Register-ScheduledJob -Trigger $trigger -Name FileJob -ScriptBlock {$args[0]}
But it doesn't work. What's wrong?
I use the following Powershell snippet to create Windows Scheduled Tasks.
$action = New-ScheduledTaskAction -Execute 'application.exe' -Argument '-NoProfile -WindowStyle Hidden'
$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:10
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "FileJob" -Description "FileJob"
This is what I use to create my task:
#The first command uses the New-ScheduledTaskAction cmdlet to assign the action variable $A to the executable file tskmgr.exe
$A = New-ScheduledTaskAction -Execute "C:\WINDOWS\SysWOW64\WindowsPowerShell\v1.0\powershell.exe" -file "C:\directory\powershell.ps1"
#The second command uses the New-ScheduledTaskTrigger cmdlet to assign the trigger variable $T to the value AtLogon
$T = New-ScheduledTaskTrigger -weekly -DaysOfWeek Saturday -At 7am
#The third command uses the New-ScheduledTaskSettingsSet cmdlet to assign the settings variable $S to a task settings object
$S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit 1:00:00 -MultipleInstances 2
#The fourth command assigns the principal variable to the New-ScheduledTaskPrincipal of the scheduled task, Domain\Username
$P = New-ScheduledTaskPrincipal -UserId domain\gMSAaccount$ -LogonType Password -RunLevel Highest
#The fifth command sets the description varible to $D for the task definition
$D = "Insert your description here"
#Registers the new scheduled task and defines it by using the $D variable
Register-ScheduledTask Name_of_Task -Action $A -Trigger $T -Settings $S -Principal $P -Description $D<p>
I found that using gMSA accounts are the best in an active directory environment. Implement gMSA The requirement is that in order to use gMSA, you must create your task with a powershell script or schtask.exe.
I cant seem to figure out how to create a new scheduled task that is triggered daily and repeats every 30 minutes. I have been going in circles.
Everything about this below works for setting the task I want, but only triggered once.
#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"
#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"
####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden `"$psscript `'$sourcedir`' `'$destdir`' `'$archivepassword`'`""
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask EncryptSyncTEST -InputObject $ST -User $username -Password $password
If I change -Once to -Daily I lose the -RepetitionInterval flags. And if I come back to update the task to daily after registering it, it wipes the repeating trigger.
This isn't an uncommon scheduling method, and is easily applied through the task scheduler UI. I feel like it is probably simple but I am missing it.
Any help is appreciated.
EDIT: Addressing the duplicate question. The question in the post "Powershell v3 New-JobTrigger daily with repetition" is asking the same. But as I commented earlier, none of the answers solve the issue. The marked answer does exactly what I already have here, it sets a task with a -Once trigger, then updates it to repeat every 5 minutes for 1 day. After the first day that task will never be triggered again. It does not address the issue of triggering a task everyday with repetition and duration until the next trigger.
The other three answers on that post are also not addressing the question. I do not know why it was marked answered, because it is not correct. I fully explored those replies before I posted this question. With that post having aged and being marked as answered I created this question.
Note: I have found a workaround, but not a great one. At current it seems the easiest way to define custom triggers using powershell is to manipulate the Scheduled Task XML and import it directly using Register-ScheduledTask
While the PowerShell interface for scheduled task triggers is limited, it turns out if you set the RepetitionDuration to [System.TimeSpan]::MaxValue, it results in a duration of "Indefinitely".
$trigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 5) `
-RepetitionDuration ([System.TimeSpan]::MaxValue)
Tested on Windows Server 2012 R2 (PowerShell 4.0)
Here is a way of creating a scheduled task in Powershell (v5 on my machine, YMMV) that will start at 12AM every day, and repeat hourly for the rest of the day. Therefore it will run indefinitely. I believe this is a superior approach vs setting -RepetitionDuration to ([timespan]::MaxValue) as I commented earlier, as the trigger will show up in the Task Scheduler as:
At 12:00 AM every day - After triggered, repeat every 30 minutes for a duration of 1 day.
Rather than the date on which the task was registered appearing in the trigger as approaches that use -Once -At 12am result in, create the trigger as a simple -Daily -At 12am, register the task then access some further properties on the tasks Triggers property;
$action = New-ScheduledTaskAction -Execute <YOUR ACTION HERE>
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -TaskName "MyTask" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" //Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT30M" //Repeat every 30 minutes, use PT1H for every hour
$task | Set-ScheduledTask
//At this point the Task Scheduler will have the desirable description of the trigger.
Create base trigger:
$t1 = New-ScheduledTaskTrigger -Daily -At 01:00
Create secondary trigger (omit -RepetitionDuration for an indefinite duration):
$t2 = New-ScheduledTaskTrigger -Once -At 01:00 `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)
Take repetition object from secondary, and insert it into base trigger:
$t1.Repetition = $t2.Repetition
Bob's your uncle:
New-ScheduledTask -Trigger $t1 -Action ...
I'm sure there must be a better way, but this is my current workaround.
I created a task with the triggers I wanted then grabbed the XML it generated.
Below I am creating the task, then pulling the XML for that new task, replacing my triggers, then un-registering the task it and re-registering it with the updated XML.
Long term, I will probably just use the full XML file for the task and replace the strings as needed, but this works for now.
#Credentials to run task as
$username = "$env:USERDOMAIN\$env:USERNAME" #current user
$password = "notmypass"
#Location of Scripts:
$psscript = "C:\test\test.ps1"
$Sourcedir ="C:\testsource\"
$destdir = "C:\testdest\"
$archivepassword = "notmypass"
####### Create New Scheduled Task
$action = New-ScheduledTaskAction -Execute "Powershell" -Argument "-WindowStyle Hidden '$EncryptSync' '$sourcedir' '$destdir' '$archivepassword'"
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 30)
$settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable
$ST = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask "EncryptSyncTEST" -InputObject $ST -User $username -Password $password
[xml]$EncryptSyncST = Export-ScheduledTask "EncryptSyncTEST"
$UpdatedXML = [xml]'<CalendarTrigger xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Repetition><Interval>PT30M</Interval><Duration>P1D</Duration><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2013-11-18T07:07:15</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>'
$EncryptSyncST.Task.Triggers.InnerXml = $UpdatedXML.InnerXML
Unregister-ScheduledTask "EncryptSyncTEST" -Confirm:$false
Register-ScheduledTask "EncryptSyncTEST" -Xml $EncryptSyncST.OuterXml -User $username -Password $password
The easiest method I found to accomplish this is to use schtasks.exe. See full documentation at https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx
schtasks.exe /CREATE /SC DAILY /MO 1 /TN 'task name' /TR 'powershell.exe C:\test.ps1' /ST 07:00 /RI 30 /DU 24:00
This creates a task that runs daily, repeats every 30 minutes, for a duration of 1 day.
https://stackoverflow.com/a/54674840/9673214
#SteinIP solution worked for me with slight modification
In 'create secondary trigger' part added '-At' parameter with same value as in 'create base trigger' part.
Create base trigger
$t1 = New-ScheduledTaskTrigger -Daily -At 01:00
Create secondary trigger:
$t2 = New-ScheduledTaskTrigger -Once -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55) -At 01:00
Do the magic:
$t1.Repetition = $t2.Repetition
New-ScheduledTask -Trigger $t1 -Action ...
Another way to do it is just to create multiple triggers like so:
$startTimes = #("12:30am","6am","9am","12pm","3pm","6pm")
$triggers = #()
foreach ( $startTime in $startTimes )
{
$trigger = New-ScheduledTaskTrigger -Daily -At $startTime -RandomDelay (New-TimeSpan -Minutes $jitter)
$triggers += $trigger
}
If you wanna a infinate Task duration on Windows 10 just use this (Do not specify -RepetitionDuration)
$action = New-ScheduledTaskAction -Execute (Resolve-Path '.\main.exe')
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "GettingDataFromDB" -Description "Dump of new data every hour"
Here's another variation that seems to work well for this old chestnut, but is less complex than some of the other solutions. It has been tested on Server 2012 R2, Server 2016 and Server 2019, with the default PS version on each OS. "Merging" the triggers didn't work for me on 2012. Didn't bother with the others.
The steps are simple:
Create the scheduled task with the basic schedule first
Extract the details from the new task
Modify the trigger repetition/duration
Update the existing task with the modified version
The example consists of a daily task that repeats every hour for a day (I've set it to 23 hours to make the date/time syntax a little clearer). The same timespan format is used for Duration and Interval.
# create the basic task trigger and scheduled task
$trigger = New-ScheduledTaskTrigger -Daily -At 15:55
$Settings = New-ScheduledTaskSettingsSet –StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -Setting $Settings -User $User
# Get the registered task parameters
$task = Get-Scheduledtask $TaskName
# Update the trigger parameters to the repetition intervals
$task.Triggers[0].Repetition.Duration = "P0DT23H0M0S"
$task.Triggers[0].Repetition.Interval = "P0DT1H0M0S"
# Commit the changes to the existing task
Set-ScheduledTask $task
Note that if your task has multiple triggers - although that'd be unusual if you have a repetition interval - you need to modify whichever trigger needs the repetitions. The example only has a single trigger, so we just select the first (and only) member of the list of triggers - $task.Triggers[0]
The timespan is ISO 8601 format - it's a string with no spaces. The required numeric value precedes the time designation (e.g. 1H for one hour, not H1). The string must contain all the time designations as listed, with a 0 substituting for any empty values. The P ("period") at the beginning indicates it's a duration rather than a timestamp.
P(eriod)0D(ays)T(ime)0H(ours)0M(inutes)0S(econds)
P0DT1H0M0S = 0 days, 1 hours, 0 minutes, 0 seconds
P0DT0H15M30S = 0 days, 0 hours, 15 minutes, 30 seconds
You can use a similar method to modify the trigger if you want to change a start time on a task. This applies to -Once or -Daily tasks.
$task = Get-ScheduledTask $taskname
$d = ([DateTime]::now).tostring("s") # 2021-11-30T17:39:31
$task.Triggers[0].StartBoundary = $d
Set-ScheduledTask $task
Old question and I'm not sure if the powershell cmdlets are a requirement. But I just use schtasks.
If you want to run every 15 minutes:
schtasks /f /create /tn taskname `
/tr "powershell c:\job.ps1" /ru system `
/sc minute /mo 15 /sd 01/01/2001 /st 00:00
This will 'trigger' on 1/1/2001 midnight and run every 15 minutes. so if you create it today, it'll just run on the next event interval.
If you want it to 'trigger' every single day, you can do this:
schtasks /f /create /tn taskname `
/tr "powershell c:\job.ps1" /ru system `
/sc daily /sd 01/01/2001 /st 10:00 /du 12:14 /ri 15
This will 'trigger' on 1/1/2001 10am, and run every 15 minutes for 12 hours and 14 minutes. so if you start it today, it'll just run on the next event interval.
I normally run my 'every 15 minutes' like the top one and my 'every day for x times' like the bottom. So if i need to run something at say 10am and 2pm, i just change the /du on the second one to 5 hours and the /ri to 4. then it repeates every 4 hours, but only for 5 hours. Technically you may be able to put it at 4:01 for duration, but i generally give it an hour to be safe.
I used to use the task.xml method and was having a really tough time with the second scenario until I noticed in a task.xml that was exported it basically just has something like this below.
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT3H</Interval>
<Duration>PT15H</Duration>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2017-11-27T05:45:00</StartBoundary>
<ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
This was for a job that ran every 3 hours between 5:45 and 7:45. So I just fed the interval and duration into a daily schedule command and it worked fine. I just use an old date for standardization. I'm guessing you could always start it today and then it would work the same.
To run this on remote servers I use something like this:
$sb = { param($p); schtasks /f /create /tn `"$p`" /tr `"powershell c:\jobs\$p\job.ps1`" /ru system /sc daily /sd 01/01/2001 /st 06:00 /du 10:00 /ri (8*60) } }
Invoke-Command -ComputerName "server1" -ScriptBlock $sb -ArgumentList "job1"
Working in Windows 10
Set-ExecutionPolicy RemoteSigned
$action=New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'C:\Users\hp\Anaconda3\python.exe C:\Users\hp\Desktop\py.py'
$trigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepetitionDuration (New-TimeSpan -Days (365 * 20))
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ts2" -Description "tsspeech2"