Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop existing instance option when creating windows scheduled task using PowerShell

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"
like image 917
tytheguy Avatar asked Oct 14 '25 20:10

tytheguy


1 Answers

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"