Advertisement
MadScientist2017

Script Out SQL Agent Jobs (SQL Server)

Aug 29th, 2017
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # REF: http://sqlblog.com/blogs/allen_white/archive/2012/05/02/script-and-migrate-agent-jobs-between-servers-using-powershell.aspx
  2. # REF: https://www.johnsansom.com/script-sql-server-agent-jobs-using-powershell/
  3.  
  4. # This script is my attempt at merging of the above two scripts. -dougl
  5.  
  6. # To execute: Script Out SQL Agent Jobs.ps1 <ServerNameListFile>
  7.  
  8. param([String]$ServerListPath)
  9.  
  10. #write-host "Parameter: $ServerListPath"
  11.  
  12. #Load the input file into an Object array
  13. $ServerNameList = get-content -path $ServerListPath
  14.  
  15. #Load the SQL Server SMO Assemly
  16. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
  17.  
  18. #Create a new SqlConnection object
  19. $objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
  20.  
  21. #For each server in the array do the following.
  22. foreach($ServerName in $ServerNameList)
  23. {
  24.     Write-Host "Beginning with Server: $ServerName"
  25.  
  26.     Try
  27.     {
  28.         $objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
  29.             Write-Host "Trying to connect to SQL Server instance on $ServerName..." -NoNewline
  30.             $objSQLConnection.Open() | Out-Null
  31.             Write-Host "Success."
  32.         $objSQLConnection.Close()
  33.     }
  34.     Catch
  35.     {
  36.         Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  37.         $errText =  $Error[0].ToString()
  38.             if ($errText.Contains("network-related"))
  39.         {Write-Host "Connection Error. Check server name, port, firewall."}
  40.  
  41.         Write-Host $errText
  42.         continue
  43.     }
  44.  
  45.     # Won't be using this object again
  46.     Remove-Variable -Name objSQLConnection
  47.  
  48.     #If the output folder does not exist then create it
  49.     $OutputFolder = ".\$ServerName"
  50.     if (!(Test-Path $OutputFolder))
  51.     {
  52.         write-host ("Creating directory: " + $OutputFolder)
  53.         New-Item -ItemType directory -Path $OutputFolder
  54.     }
  55.     else
  56.     {
  57.         write-host ("Directory already exists: " + $OutputFolder)
  58.     }
  59.  
  60.     #DEBUG write-host "File: $(".\$OutputFolder\" + $($_.Name -replace '\\', '') + ".job.sql")"
  61.  
  62.     # Connect to the instance using SMO
  63.     $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $ServerName
  64.  
  65.     #DEBUG write-host ("SQL Server Edition: " + $s.Edition)
  66.     #DEBUG write-host ("SQL Agent ErrorLogFile: " + $s.JobServer.ErrorLogFile)
  67.    
  68.     # Instantiate the Scripter object and set the base properties
  69.     $scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($ServerName)
  70.  
  71.     write-host ("SCRP ToString():" + $scrp.ToString())
  72.     write-host ("Test scrp - Server: " + $scrp.Server)
  73.  
  74.     #The next step is to set the properties for the script files:
  75.     $scrp.Options.ScriptDrops = $False
  76.     $scrp.Options.WithDependencies = $False
  77.     $scrp.Options.IncludeHeaders = $True
  78.     $scrp.Options.AppendToFile = $False
  79.     $scrp.Options.ToFileOnly = $True
  80.     $scrp.Options.ClusteredIndexes = $True
  81.     $scrp.Options.DriAll = $True
  82.     $scrp.Options.Indexes = $False
  83.     $scrp.Options.Triggers = $False
  84.     $scrp.Options.IncludeIfNotExists = $True
  85.  
  86.     #Now, we can cycle through the jobs and create scripts for each job on the server.
  87.  
  88.     # Create the script file for each job
  89.     foreach ($job in $s.JobServer.Jobs)
  90.     {
  91.         $jobname = $job.Name
  92.        
  93.         #DEBUG write-host ("Job: " + $jobname)
  94.  
  95.         $jobfilename = ($OutputFolder + "\" + $jobname + ".job.sql")
  96.         $scrp.Options.FileName = $jobfilename
  97.  
  98.         #DEBUG write-host "Filename: $jobfilename"
  99.  
  100.         #This line blows up
  101.         $scrp.Script($job)
  102.     }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement