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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With