I can't figure out why the below code won't work:
Function createFirefoxTask() {
$schedule = new-object -com Schedule.Service
$schedule.connect()
$tasks = $schedule.getfolder("\").gettasks(0)
foreach ($task in ($tasks | select Name)) {
echo "TASK: $task.name"
if($task.equals("FirefoxMaint")) {
write-output "$task already exists"
break
}
}
}
createFirefoxTask
The output I get is this:
FirefoxMaint
TASK: @{Name=FirefoxMaint}.name
TASK: @{Name=Task1}.name
TASK: @{Name=Task2}.name
TASK: @{Name=Task3}.name
TASK: @{Name=Task4}.name
TASK: @{Name=Task5}.name
If I echo $task.name
from the shell without going through the script, it properly displays the name.
To retrieve the existing tasks in the task scheduler using PowerShell, we can use the PowerShell command Get-ScheduledTask. We can use the Task Scheduler GUI to retrieve the scheduled tasks. To retrieve using PowerShell, use the Get-ScheduledTask command.
Windows Scheduled tasks history is written to an event log. If you open Event Viewer and go to: Event Viewer (Local) / Applications and Services Logs / Microsoft / Windows / TaskScheduler / Optional, you will see all the Task Histories.
You can monitor scheduled tasks by accessing 'Security Logs' in the 'Event Viewer'. You can filter your log to look for the following event. Event ID: 4698 describes a task that has been scheduled.
In order to prevent errors with Get-ScheduledTask in case the task doesn't exist - you might want to consider doing :
$taskName = "FireFoxMaint"
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }
if($taskExists) {
# Do whatever
} else {
# Do whatever
}
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