Create-MSSQLJob-UsingSMO


posted by Richard Giles
10-06-2008

Downloads: 504
File size: 4.1kB
Views: 2,257

Embed
Create-MSSQLJob-UsingSMO
  1. ## ===================================================================== 
  2. ## Title       : Create-MSSQLJob-UsingSMO 
  3. ## Description : Create a daily SQL job to call a powershell script 
  4. ## Author      : Idera 
  5. ## Date        : 9/1/2008 
  6. ## Input       : -server <server\instance> 
  7. ##                      -jobName <jobname> 
  8. ##               -taskDesc <job description> 
  9. ##                      -category <job category> 
  10. ##                   -hrSched <n - hour military time> 
  11. ##               -minSched <n - minute military time> 
  12. ##                      -psScript <path\script.ps1> 
  13. ##                   -verbose  
  14. ##                   -debug     
  15. ## Output      : SQL Job, job step and schedule for running a PowerShell script 
  16. ## Usage            : PS> . Create-MSSQLJob-UsingSMO -server MyServer -jobName MyJob  
  17. ##                          -taskDesc Perform something... -category Backup Job  
  18. ##                            -hrSched 2 -psScript C:\TEMP\test.ps1 -minSched 0 -v -d 
  19. ## Notes            : Adapted from an Allen White script 
  20. ## Tag            : SQL Server, SMO, SQL job 
  21. ## Change Log  : 
  22. ## ===================================================================== 
  23.  
  24. param 
  25.       [string]$server = "(local)"
  26.     [string]$jobname = "PowerShellJob"
  27.     [string]$taskDesc = "Perform some task"
  28.     [string]$category = "[Uncategorized (Local)]"
  29.     [string]$psScript = "C:\TEMP\test.ps1"
  30.     [int]$hrSchedule = 2, 
  31.     [int]$minSchedule = 0, 
  32.     [switch]$verbose
  33.     [switch]$debug 
  34.  
  35. function main() 
  36.     if ($verbose) {$VerbosePreference = "Continue"
  37.     if ($debug) {$DebugPreference = "Continue"
  38.     Create-MSSQLJob-UsingSMO $server $jobName $taskDesc $category $psScript $hrSchedule $minSchedule 
  39.  
  40. function Create-MSSQLJob-UsingSMO($server, $jobName, $taskDesc, $category, ` 
  41.                                     $psScript, $hrSched, $minSched
  42.     # TIP: using PowerShell to create an exception handler 
  43.    trap [Exception]  
  44.     
  45.       write-error $("TRAPPED: " + $_.Exception.Message); 
  46.       continue
  47.    
  48.  
  49.     # Load SMO assembly 
  50.     [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO'
  51.      
  52.     # Instantiate SMO server object 
  53.     # TIP: instantiate object with parameters 
  54.     $namedInstance = new-object ('Microsoft.SqlServer.Management.Smo.Server') ($server
  55.      
  56.     # Instantiate an Agent Job object, set its properties, and create it 
  57.     Write-Debug "Create SQL Agent job ..." 
  58.     $job = new-object ('Microsoft.SqlServer.Management.Smo.Agent.Job') ($namedInstance.JobServer, $jobName
  59.     $job.Description = $taskDesc 
  60.     $job.Category = $category 
  61.     $job.OwnerLoginName = 'sa' 
  62.      
  63.     # Create will fail if job already exists 
  64.     #  so don't build the job step or schedule 
  65.     if (!$job.Create()) 
  66.     
  67.         # Create the step to execute the PowerShell script 
  68.         #   and specify that we want the command shell with command to execute script,  
  69.         Write-Debug "Create SQL Agent job step..." 
  70.         $jobStep = new-object ('Microsoft.SqlServer.Management.Smo.Agent.JobStep') ($job, 'Step 1'
  71.         $jobStep.SubSystem = "CmdExec" 
  72.         $runScript = "powershell " + "'" + $psScript + "'" 
  73.         $jobStep.Command = $runScript 
  74.         $jobStep.OnSuccessAction = "QuitWithSuccess" 
  75.         $jobStep.OnFailAction = "QuitWithFailure" 
  76.         $jobStep.Create() 
  77.          
  78.         # Alter the Job to set the target server and tell it what step should execute first 
  79.         Write-Debug "Alter SQL Agent to use designated job step..." 
  80.         $job.ApplyToTargetServer($namedInstance.Name
  81.         $job.StartStepID = $jobStep.ID 
  82.         $job.Alter() 
  83.      
  84.         # Create start and end timespan objects to use for scheduling 
  85.         # TIP: using PowerShell to create a .Net Timespan object 
  86.         Write-Debug "Create timespan objects for scheduling the time for 2am..." 
  87.         $StartTS = new-object System.Timespan($hrSched, $minSched, 0) 
  88.         $EndTS = new-object System.Timespan(23, 59, 59) 
  89.          
  90.         # Create a JobSchedule object and set its properties and create the schedule 
  91.         Write-Debug "Create SQL Agent Job Schedule..." 
  92.         $jobSchedule = new-object ('Microsoft.SqlServer.Management.Smo.Agent.JobSchedule') ($job, 'Sched 01'
  93.         $jobSchedule.FrequencyTypes = "Daily" 
  94.         $jobSchedule.FrequencySubDayTypes = "Once" 
  95.         $jobSchedule.ActiveStartTimeOfDay = $StartTS 
  96.         $jobSchedule.ActiveEndTimeOfDay = $EndTS 
  97.         $jobSchedule.FrequencyInterval =
  98.         $jobSchedule.ActiveStartDate = get-date 
  99.         $jobSchedule.Create() 
  100.          
  101.         Write-Host SQL Agent Job: $jobName was created 
  102.     
  103.  
  104. main 
Filed under: , , ,

Create a SQL Server job to call a PowerShell script

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.