I am creating a PowerShell script which will create a scheduled task.
Using the Windows GUI, in the settings dialogue, I can set it to "Stop the existing instance" which will close the program if it's already running.
When exporting this task via XML the field is labelled as:
<Settings>
<MultipleInstancesPolicy>StopExisting</MultipleInstancesPolicy>
</Settings>
However, when writing this in PowerShell I only have the options for IgnoreNew, Parallel and Queue.
Is there a way to use the StopInstace via PowerShell?
Here is my code:
$Action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c 'command'"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days (365 * 20)) -RepetitionInterval (New-TimeSpan -Minutes 33)
**$Setting = New-ScheduledTaskSettingsSet -MultipleInstances StopInstance**
Register-ScheduledTask -Action $Action -Trigger $Trigger -Setting $Setting -TaskName "Microsoft Windows > Monitoring Service" -Description "Command Runner"
The StopInstance enum value currently is not supported by ScheduledTasks module.
You can directly set CIM property value instead:
$Action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c 'ver'"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionDuration (New-TimeSpan -Days (365 * 20)) -RepetitionInterval (New-TimeSpan -Minutes 33)
$Setting = New-ScheduledTaskSettingsSet
$Setting.CimInstanceProperties.Item('MultipleInstances').Value = 3 # 3 corresponds to 'Stop the existing instance'
Register-ScheduledTask -Action $Action -Trigger $Trigger -Setting $Setting -TaskName "Microsoft Windows > Monitoring Service" -Description "Command Runner"
Related
I am trying to automate creation of system restore points using Powershell (v7.2.6). Following are the commands that I have run:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument 'ExecutionPolicy Bypass -Command "Checkpoint-Computer -Description \"Auto Backup\" -RestorePointType \"MODIFY_SETTINGS\""'
$trigger = New-ScheduledTaskTrigger -Weekly -At 9am
$stsettings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -StartWhenAvailable
These work fine but when I run...
Register-ScheduledTask -TaskName "Auto System Backup" -RunLevel Highest -Action $action -Trigger $trigger -Settings $stsettings
...I get the an error message: Register-ScheduledTask: The parameter is incorrect.
Not sure which parameter is incorrect though. What am I doing wrong here?
The below command is wrong. There is no -Monthly parameter in New-ScheduledTaskTrigger. Also what you have specified does not make sense, Monthly 9am??
$trigger = New-ScheduledTaskTrigger -Monthly -At 9am
I'm trying to create a new Windows Scheduler Task, which will run some sync job.
The things are:
I want to use a separated service account, not Administrator
I want to run a job not to get tied with service account's password change. In Windows Scheduler Task it is a "Do not store password" check button ("-LogonType S4U" option below)
Job should be created by Powershell as job creation should be automated
I'm running commands below under local Administrator and get an error:
PS C:\Temp> $TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
PS C:\Temp> $TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
PS C:\Temp> $TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
PS C:\Temp> $TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
PS C:\Temp> Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
Register-ScheduledTask : Access is denied.
At line:1 char:1
+ Register-ScheduledTask -Action $TaskAction -Description "<DESC>" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Register-ScheduledTask
<SERVICE_USER> has been added to "Log on as a batch job" local policy.
Permissions for C:\Windows\Tasks or C:\Windows\System32\Tasks set with iCACLS does not help.
I've even added <SERVICE_USER> to local Administrators group - the same error.
If I do everything via GUI - it asks me <SERVICE_USER> credentials and works fine.
What permissions do I lack?
The thing was in user, running PS: if your need a "Do not store password" check button in your job, you need all the code above in PS console being ran under <SERVICE_USER> (you need to add <SERVICE_USER> to "Allow log on locally" local policy).
An Ansible example:
- name: Create and register sync task
win_shell: |
$TaskAction = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "<ARGUMENTS>"
$TaskSettingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 3) -MultipleInstances IgnoreNew -DontStopIfGoingOnBatteries
$TaskTrigger = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 40) -Weekly -DaysOfWeek Saturday -At 7:30am
$TaskPrincipal = New-ScheduledTaskPrincipal -UserId "<SERVICE_USER>" -LogonType S4U
Register-ScheduledTask -Action $TaskAction -Description "<DESC>" -Settings $TaskSettingsSet -Principal $TaskPrincipal -TaskName "<TASK_NAME>" -TaskPath "\" -Trigger $TaskTrigger
vars:
ansible_become: yes
ansible_become_method: runas
ansible_become_user: <SERVICE_USER>
register: sync_task
I run the following command in PowerShell:
Schtasks /create /tn "Scheduler Test4" /sc minute /tr "PowerShell -command cp c:\Users\myUsername\Desktop\myCat/main.txt c:/Users/myUsername/Desktop/myCat_backup/"
It doesn't work. I desire that main.txt gets copied into the backup directory. When I look in myCat_backup/ there is no main.txt, even if I remove the -command flag. Please help.
This script will create a sheduled task that runs powershell every minute as the user "System":
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -NoLogo -NoProfile -command Copy-Item C:\temp\Source\main.txt C:\temp\Target\'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'Scheduler Test' -InputObject $Task -User 'system'
It turns out once I restarted my device, the script started working. Furthermore, I can now create more tasks and Powershell is recognizing the commands created using Schtasks without restarting.
I'm trying to use PowerShell to create (and replace) a scheduled Windows task. I found the docs for the relevant PowerShell commands and as far as I can see, I have everything right:
$action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
$now = Get-Date
$interval = New-TimeSpan -Seconds 60
$forever = [System.TimeSpan]::MaxValue
$trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval -RepetitionDuration $forever
$settings = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName 'TEST' -InputObject $task
However, running this, I get a cryptic error:
Register-ScheduledTask : The task XML contains a value which is incorrectly formatted or out of range.
The error message is useless - how do I debug it?
What XML? At what path?
Which value?
What range?
This answer says to now use TimeSpan.MaxValue so I used a 100 years instead:
$forever = $now.AddYears(100) - $now # [System.TimeSpan]::MaxValue doesn't work
However, the error remains the same.
I googled around and found a suggestion to look into HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree, however, my task doesn't appear in there.
What to do?
Just don't set the -RepetitionDuration parameter at all.
By default, it will do it indefinitely.
$action = New-ScheduledTaskAction -Execute "node" -Argument "C:/scripts/task.js"
$now = Get-Date
$interval = New-TimeSpan -Seconds 60
$forever = [System.TimeSpan]::MaxValue
$trigger = New-ScheduledTaskTrigger -Once -At $now -RepetitionInterval $interval
$settings = New-ScheduledTaskSettingsSet
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName 'TEST' -InputObject $task
Task created using the script above
As for your error, the complete error I had when attempting to execute your script was clear enough. It specifically indicated that the "Max" timespan was not an accepted value.
Register-ScheduledTask : The task XML contains a value which is
incorrectly formatted or out of range.
(8,42):Duration:P99999999DT23H59M59S At line:8 char:1
+ Register-ScheduledTask -TaskName 'TEST' -InputObject $task
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask)
[Register-ScheduledTask], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041318,Register-ScheduledTask
To ease some of my work I have created a powershell script which needs to :
Run at startup.
Run with admin rights as it has to write in c:\program files folder.
I created the startup service using powershell like this :
function MakeStartupService
{
Write-Host "Adding script as a startup service"
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15
Try
{
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name" -EA Stop
}
Catch [system.exception]
{
Write-Host "Looks like an existing startup service exists for the same. Overwriting existing job"
Unregister-ScheduledJob "Job-name"
Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name"
}
}
The job is registered as a startup service successfully and is visible inside task scheduler. If I start it using Start-Job -DefinitionName Job-name or by right clicking from Task Scheduler, it works fine but it doesn't start when windows starts.
Currently I am testing this on my personal Windows 10 system, and have checked in another windows 10 system but the behavior remained name. I am attaching screenshot of task scheduler window for this job.
Sorry if this questions sounds repeated or dumb (I am a beginner in powershell), but believe me, none of the solutions I found online worked for this.
Thanks in advance !!
This is code that is already in production that I use. If it does not work for you, you must have something else going on with your system.
function Invoke-PrepareScheduledTask
{
$taskName = "UCM_MSSQL"
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}
# TODO: EDIT THIS STUFF AS NEEDED...
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\Invoke-MYSCRIPT.ps1"'
$trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
$definition = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Description "Run $($taskName) at startup"
Register-ScheduledTask -TaskName $taskName -InputObject $definition
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
# TODO: LOG AS NEEDED...
if ($task -ne $null)
{
Write-Output "Created scheduled task: '$($task.ToString())'."
}
else
{
Write-Output "Created scheduled task: FAILED."
}
}
If it works, it's not a script problem. Assign it to the SYSTEM account or make a separate service account instead of the Gagan account shown. Make sure that service account has "Permission to run as batch job" in your local security policy.
If you want to get rid of that "on battery" crap, add
-DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
to New-ScheduledTaskSettingsSet options.
So, in Kory Gill answer, $settings becomes:
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
so task will be created to get rid of battery restrictions.
If you just want to modify an existing task, you can do it with:
Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
or from cmd:
powershell -executionpolicy bypass Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)
Please check the checkbox for "Run with highest privileges" for the task in the task scheduler and try again. Currently in the screenshot above it is unchecked.
I have circled it below in red for your easy reference: