Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing to see if a scheduled task exist in powershell

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.

like image 635
hax0r_n_code Avatar asked Jul 17 '13 15:07

hax0r_n_code


People also ask

How do I view scheduled tasks in PowerShell?

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.

How do I know if scheduled task ran?

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.

How do I see scheduled tasks on a server?

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.


1 Answers

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
}
like image 167
Jochen van Wylick Avatar answered Oct 17 '22 09:10

Jochen van Wylick