Powershell - Schedule a Task to run a PS script with parameters - powershell

I'm trying to schedule a task that runs a PS script with parameters. But I believe I'm missing an escape character somewhere or my ' and " are in the wrong place. I can't seem to get it to work properly without it splitting the action argument. Below is my code:
$employeeID = "1234"
$employee = "email#email.com"
$restoretime = (Get-date).AddHours(12)
$restoreuser = "$($employee) Offboarding"
$trigger = New-ScheduledTaskTrigger -once -At $restoretime
$taskAction = New-ScheduledTaskAction -Execute '%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument `
-Command "& 'C:\Location\testing.ps1' -employeeID '$($employeeID)' -employee '$($employee)'"
Register-ScheduledTask -TaskName $restoreuser -Action $taskAction -Trigger $trigger
I get this result (see image)
Any help would be appreciated!
I've tried the approaches here with no luck!

Related

Scheduled task created via powershell, to run powershell code generating Error Value: 2147942667

I want to run the following powershell code as a scheduled task, also deployed via powershell.
$postParams = #{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams
I'm using the following code to create a Windows scheduled task that should run the code.
$repeat = (New-TimeSpan -Minutes 5)
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `-Argument '-NoProfile -WindowStyle Hidden -command "& {$postParams = #{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams}"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update IP" -Description "IP update"
While this successfully creates the task itself, running this provides the following error in the task history, and does not execute the code
Task Scheduler failed to launch action "Powershell.exe" in instance "{9b40f292-92cc-47dc-9041-d3b2d266d82b}" of task "\Update IP". Additional Data: Error Value: 2147942667.
Searching this error online typically suggests its a quote issue when specifying paths and I can't find much else on the subject.
I'd like to avoid running this from it's own .ps1 file if possible, and to get it work in the above manner (due to the way this is being deployed).
Can anyone assist please?
you have an extra back tick ( "`" ) before the -Argument parameter due to which the task does not receive arguments, it's must be like this:
$repeat = (New-TimeSpan -Minutes 5)
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {$postParams = #{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams}"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update IP" -Description "IP update"

Powershell Script To Find/Run Scheduled Task or Create

I am trying to figure out how to write a PowerShell script to find and run a scheduled task, or if it is not there then to create it. Here is what I have built so far. The else statement works but the first task does not.
$taskName = "crebackup"
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName}
if($taskExists) {
Start-ScheduledTask -TaskName "crebackup"}
else {
$action = New-ScheduledTaskAction -Execute “C:\POSNation\SQLBackup\sqlbackup.exe”
$Trigger = New-ScheduledTaskTrigger -Daily -At 3am
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'crebackup' -InputObject $Task -User 'usernamehere' -Password 'passwordhere'}
In this case the sqlbackup.exe task needed the working directory to start in. This is displayed as "Start in (optional)" when you look at the task using Task Scheduler. To add that, use this for the $action variable:
$action = New-ScheduledTaskAction -WorkingDirectory "C:\POSNation\SQLBackup" -Execute "C:\POSNation\SQLBackup\sqlbackup.exe"
Also, make sure scripts don't have any smart quotes in them(“, ”). Smart quotes are often automatically generated by word processors and some websites. I replaced the smart quotes in the example above.

how to configure "stop the task if it runs longer than" for schtasks.exe

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

Schedule running executable using powershell

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.

Scheduled Job through PowerShell quits after 3 days

I have a script that can legitimately run much longer than 3 days (it's a command queuing script, so it has a lot of pauses in it waiting for a job to complete). I'm using the PowerShell Register-ScheduledJob cmdlet to create the job.
Everything works great except, by default, the Windows Task Scheduler will stop the script if it hasn't completed after 3 days. I can work around this by going in the GUI and unchecking the 'Stop the task if it runs longer than: 3 days' check box. I need to be able to 'uncheck' that box via Powershell code. Here's how I'm scheduling it currently:
$immediate = (get-date).AddMinutes(2).ToString("MM/dd/yyyy HH:mm")
$scheduled_date = get-date -Format "yyyyMMMd-HHMMss"
$trigger = New-JobTrigger -Once -At $immediate
$sjo = New-ScheduledJobOption -RunElevated
Register-ScheduledJob -Name "SVC Migrations - $scheduled_date" -ScriptBlock {powershell.exe -File C:\scripts\addvdiskcopy_queue.ps1 } -Trigger $trigger -ScheduledJobOption $sjo >> C:\scripts\temp\job_scheduled.txt
Again, everything works great with this until 72 hours hits. Any help is appreciated!
Thanks!
New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0
This returns an object that can be passed to Register-ScheduledJob's -Settings argument. For example:
Register-ScheduledJob `
-Settings $(New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0) `
# ...further arguments...
Just figured this out on Server 2012R2 without having to use the external DLL.
Works with Register-ScheduledTask but haven't tested with Register-ScheduledJob.
I created the with Register-ScheduledTask in a way similar to the above but without the ExecutionTimeLimit setting defined. This gave me the default of 3 days.
Then I returned the task and changed the settings as below:
$Task = Get-ScheduledTask -TaskName "MyTask"
$Task.Settings.ExecutionTimeLimit = "PT0H"
Set-ScheduledTask $Task
Check out this thread on CodePlex.
It looks like you can use the Task Scheduler Managed Library to achieve this. You'll need to download the library and load the DLL. Here is a fully working sample (just update the path to the DLL).
$TaskName = 'asdf';
# Unregister the Scheduled Job if it exists
Get-ScheduledJob asdf -ErrorAction SilentlyContinue | Unregister-ScheduledJob;
# Create the Scheduled Job
$Trigger = New-JobTrigger -At '5:00 PM' -Once;
$Option = New-ScheduledJobOption;
$Action = { Write-Host 'hi'; };
$Job = Register-ScheduledJob -Name asdf -ScriptBlock $Action -Trigger $Trigger -ScheduledJobOption $Option;
# Modify the Scheduled Job using external library
Add-Type -Path "C:\Users\Trevor\Downloads\TaskScheduler\Microsoft.Win32.TaskScheduler.dll";
$TaskService = New-Object -TypeName Microsoft.Win32.TaskScheduler.TaskService;
$Task = $TaskService.FindTask($TaskName, $true);
$Task.Definition.Settings.ExecutionTimeLimit = [System.TimeSpan]::Zero;
$Task.RegisterChanges();
I tested the library in my environment, and it works as expected. The net result is that the "Stop the task if it runs longer than" checkbox is disabled.
Use the following settings in task definition:
New-ScheduledTaskSettingsSet -ExecutionTimeLimit "PT0S"
Older post, but none of these options worked for me other than what #jdc0589 said in a comment. I run this script on an Azure VM running Windows Server 2016 Datacenter.
$action = New-ScheduledTaskAction -Execute "java.exe" `
-Argument "-jar `"D:\Selenium\selenium-grid-extras.jar`"" `
-WorkingDirectory "D:\Selenium"
$trigger = New-ScheduledTaskTrigger -AtStartup
$everyMinute = New-TimeSpan -Minutes 1
$nolimit = New-TimeSpan -Minutes 0
$settings = New-ScheduledTaskSettingsSet `
-MultipleInstances IgnoreNew `
-RestartInterval $everyMinute `
-RestartCount 999 `
-Priority 0 `
-ExecutionTimeLimit $nolimit `
-StartWhenAvailable `
-DisallowHardTerminate
Register-ScheduledTask `
-Action $action `
-Trigger $trigger `
-Settings $settings `
-TaskName "Start SGE Hub" `
-TaskPath "\Selenium Grid Extras" `
-Description "At machine startup, run SGE so that the hub can process tests without a logon" `
-RunLevel Highest `
-User "SYSTEM" `
-Force