Disable/Enable task triggers

On either Powershell V2 or V3 on a Windows 7 workstation, I’ve already presented what can be done with scheduled tasks using Com objects in the following previous posts:

Now, let’s take a specific example: the case of the Disk Defragmentation schedule

  • Display the current status of the task
  • $TaskService = New-Object -com schedule.service            
    $TaskService.Connect($env:COMPUTERNAME)            
     $TaskService.GetFolder(            
      '\Microsoft\Windows\Defrag').            
      GetTasks(1) |             
      Select Name,Path,Enabled |             
      ft -AutoSize
  • Disable the task
  • If I disable the task like this:

    # Disable the task            
    $TaskService.GetFolder(            
     '\Microsoft\Windows\Defrag').            
     GetTask('ScheduledDefrag').Enabled = $false            
    

    We get the following message from the UI, whenever I use the Tools tab in the properties of a volume.
    Defrag Task Disabled

  • Disable the Defrag task using the UI
  • If I untick the ‘Run on a schedule’ property in the schedule configuration options, we have the following:
    Defrag Task Trigger Turned Off
    The task isn’t actually disabled but only its schedule has been turned off
    Defrag task trigger turned off in mmc

  • Disable the Defrag task triggers
  • Just disabling the triggers can actually be achieved using the task registration method with a specific flag.
    task registration flags
    Source: http://msdn.microsoft.com/en-us/library/windows/desktop/aa382538%28v=vs.85%29.aspx

    $TaskService = New-Object -com schedule.service            
    $TaskService.Connect($env:COMPUTERNAME)            
    $taskDef = $TaskService.            
     GetFolder('\Microsoft\Windows\Defrag').            
      GetTask('ScheduledDefrag').Definition            
    $taskDef.Triggers|foreach-object{$_.Enabled=$false}            
    # Define a constant             
    # $TASK_CREATE_OR_UPDATE_FLAG = 0x6            
    $TASK_UPDATE_FLAG = 0x4            
    $TaskService.GetFolder('\Microsoft\Windows\Defrag').            
     RegisterTaskDefinition(            
      'ScheduledDefrag',            
      $taskDef,            
      $TASK_UPDATE_FLAG,            
      $null,            
      $null,            
      $taskDef.Principal.LogonType            
      )
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s