torsdag den 26. april 2012

Create multiple scheduled tasks across n-servers

Needed to create the same scheduled task on several servers. Using a bit of Powershell made the task a bit easier. Below functions can be used to create, delete and view scheduled tasks on a specific server:

Function Get-ScheduledTask
 {
 param([string]$ComputerName = "localhost")
 Write-Host "Computer: $ComputerName"
 $Command = "schtasks.exe /query /s $ComputerName"
 Invoke-Expression $Command
 Clear-Variable Command -ErrorAction SilentlyContinue
 Write-Host "`n"
 }
 
# EXAMPLE: Get-ScheduledTask -ComputerName Server01
 
Function Remove-ScheduledTask
 {
 param(
 [string]$ComputerName = "localhost",
 [string]$TaskName = "blank"
 )
 If ((Get-ScheduledTask -ComputerName $ComputerName) -match $TaskName)
  {
  If ((Read-Host "Are you sure you want to remove task $TaskName from $ComputerName(y/n)") -eq "y")
   {
   $Command = "schtasks.exe /delete /s $ComputerName /tn $TaskName /F"
   Invoke-Expression $Command
   Clear-Variable Command -ErrorAction SilentlyContinue
   }
  }
 Else
  {
  Write-Warning "Task $TaskName not found on $ComputerName"
  }
 }
 
# EXAMPLE: Remove-ScheduledTask -ComputerName Server01 -TaskName MyTask
 
Function Create-ScheduledTask
 {
 param(
 [string]$ComputerName = "localhost",
 [string]$RunAsUser = "System",
 [string]$TaskName = "MyTask",
 [string]$TaskRun = '"C:\Program Files\Scripts\Script.vbs"',
 [string]$Schedule = "Monthly",
 [string]$Modifier = "second",
 [string]$Days = "SUN",
 [string]$Months = '"MAR,JUN,SEP,DEC"',
 [string]$StartTime = "13:00",
 [string]$EndTime = "17:00",
 [string]$Interval = "60" 
 )
 Write-Host "Computer: $ComputerName"
 $Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /tn $TaskName /tr $TaskRun /sc $Schedule /mo $Modifier /d $Days /m $Months /st $StartTime /et $EndTime /ri $Interval /F"
 Invoke-Expression $Command
 Clear-Variable Command -ErrorAction SilentlyContinue
 Write-Host "`n"
 }
 
# EXAMPLE: Create-ScheduledTask -ComputerName MyServer -TaskName MyTask02 -TaskRun "D:\scripts\script2.vbs"

Borrowed from: this link 

2 kommentarer:

Suseela sagde ...


Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.


SAP HR training in Chennai

Unknown sagde ...

This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.
Selenium Training in Chennai