Enable disable Windows Service and Scheduled Tasks with PowerShell

Posted by

Often we may need to enable/disable Windows Services and Scheduled tasks on a Windows Server.

Below is the snippet to Enable Windows Service and Scheduled task with PowerShell:

$tasknames = "Test Task1","Test task2" $servicename = "Test Service1","Test Service2" foreach($task in $tasknames) {  ##disabling tasks on server  $taskstatus = Get-ScheduledTask -TaskName $task  if($taskstatus.State -eq "Disabled")   {    Enable-ScheduledTask -TaskName $task -Verbose   }   elseif($taskstatus.State -eq "Ready")   {   Write-Host "Task: $task already running"   }      } ##### Service checks and execution  foreach($service in $servicename)  {  $servicestatus = Get-Service $service  if($servicestatus.Status -eq "Stopped")   {    Start-Service $service  -Verbose    }    elseif($servicestatus.Status -eq "Started")    {    Write-host "Service: $service already Started"    }   } 

The below snippet shows how to disable the Scheduled tasks and Windows Service:

$tasknames = "Test Task1","Test task2" $servicename = "Test Service1","Test Service2" foreach($task in $tasknames) {  ##disabling tasks on server  $taskstatus = Get-ScheduledTask -TaskName $task  if($taskstatus.State -eq "Ready")   {    Disable-ScheduledTask -TaskName $task -Verbose   }   elseif($taskstatus.State -eq "Disabled")   {   Write-Host "Task: $task already disabled"   }      } ##### Service checks and execution  foreach($service in $servicename)  {  $servicestatus = Get-Service $service  if($servicestatus.Status -eq "Running")   {    Stop-Service $service -Force -Verbose    }    elseif($servicestatus.Status -eq "Stopped")    {    Write-host "Service: $service already stopped"    }   }  

You can save the above scripts in .ps1 format for PowerShell and call them e.g. using a .bat file.
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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.