Hey guys!
All very well?
In this post I will demonstrate how to backup all SQL Server Agent jobs via command line (CLR C# or Powershell) and export the results to SQL scripts. You can choose to generate 1 script for each job or 1 single script with all jobs in your instance.
During the migration from SQL Server 2008 R2 to 2014, this script was especially useful, since there were just over 700 jobs in the report server instance and the task of saving the script for each one manually was not viable. Backing up/restoring the msdb database could be a solution (although I don't think it's highly recommended), but as these were different versions of SQL Server, we ruled out this hypothesis.
Remember that before restoring jobs in the new environment, you will need to have created logins in the new instance. If you don't know how to back up your logins and permissions, visit the post SQL Server – How to transfer logins between instances by generating backup of users, logins and permissions.
Prerequisites
As prerequisites for using the Stored Procedure stpJob_Backup, you will also need to create the objects below:
Utils.ExecutaScriptPowerShell (Click here to access the post)
View source code
Server.cs file source code
View source code
Return class source code (Click here to access the post)
View source code
CLR Procedure source code (C#) stpJob_Backup
using System;
using System.Data.SqlTypes;
using Bibliotecas.Model;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void stpJob_Backup(SqlString Ds_Servidor, SqlString Ds_Diretorio_Destino, SqlBoolean Fl_Arquivo_Unico)
{
try
{
var comando = @"
$ServerNameList = """ + Ds_Servidor.Value + @"""
[System.Reflection.Assembly]::LoadWithPartialName(""Microsoft.SqlServer.Smo"") | Out-Null
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
foreach ($ServerName in $ServerNameList)
{
Try
{
$objSQLConnection.ConnectionString = ""Server=$ServerName;Integrated Security=SSPI;""
Write-Host ""Tentando se conectar na instância do servidor $ServerName..."" -NoNewline
$objSQLConnection.Open() | Out-Null
Write-Host ""Conectado.""
$objSQLConnection.Close()
}
Catch
{
Write-Host -BackgroundColor Red -ForegroundColor White ""Falha""
$errText = $Error[0].ToString()
if ($errText.Contains(""network-related""))
{Write-Host ""Erro de conexão à instância. Por favor, verifique o nome do servidor digitado, porta ou firewall.""}
Write-Host $errText
continue
}
$OutputFolder = """ + Ds_Diretorio_Destino.Value + @"""
$DoesFolderExist = Test-Path $OutputFolder
$null = if (!$DoesFolderExist){MKDIR ""$OutputFolder""}
$srv = New-Object ""Microsoft.SqlServer.Management.Smo.Server"" $ServerName";
if (Fl_Arquivo_Unico.Value)
{
comando += @"
$srv.JobServer.Jobs | foreach {$_.Script() + ""GO`r`n""} | out-file ""$OutputFolder\jobs.sql""";
}
else
{
comando += @"
$srv.JobServer.Jobs | foreach-object -process {out-file -filepath $(""$OutputFolder\"" + $($_.Name -replace '\\', '') + "".sql"") -inputobject $_.Script() }";
}
comando += @"
}";
var saida = Utils.ExecutaScriptPowerShell(comando);
Retorno.Mensagem(saida);
}
catch (Exception e)
{
Retorno.Erro("Erro : " + e.Message);
}
}
};
Usage examples
Now I will demonstrate how to use the Stored Procedure created to export the SQL script of all SQL Server Agent jobs. These are the current jobs for the instance.
Example 1:
In this example, I will demonstrate how to export the creation script for all jobs in the instance, with 1 sql file for each job.
EXEC CLR.dbo.stpJob_Backup
@Ds_Servidor = N'VM-DBA', -- nvarchar(max)
@Ds_Diretorio_Destino = N'C:\Temp\Jobs', -- nvarchar(max)
@Fl_Arquivo_Unico = 0 -- bit
Example 2:
In this example, I will demonstrate how to export the creation script for all jobs in the instance, with 1 sql file containing the script for all jobs.
EXEC CLR.dbo.stpJob_Backup
@Ds_Servidor = N'VM-DBA', -- nvarchar(max)
@Ds_Diretorio_Destino = N'C:\Temp\Jobs', -- nvarchar(max)
@Fl_Arquivo_Unico = 1 -- bit
Using only PowerShell and OLE Automation
If you don't want to use the CLR for this solution and just want to use PowerShell for the database, you can do that too.
Prerequisites
As prerequisites for using the procedure below, we will need some functions for manipulating files. To do this, we will use OLE Automation to manipulate these files. To learn more about this, see the post File operations using OLE Automation in SQL Server.
stpWrite_File_FSO
View source code
fncFile_Exists_FSO
View source code
stpDelete_FSO_File
View source code
Stored Procedure stpExecuta_Script_Powershell
CREATE PROCEDURE [dbo].[stpExecuta_Script_Powershell]
@Ds_Script [varchar](MAX),
@Fl_Apaga_Script [bit] = 1
AS
BEGIN
SET NOCOUNT ON
DECLARE
@QuebraLinha VARCHAR(10) = CHAR(13) + CHAR(10),
@arquivo VARCHAR(MAX),
@diretorio VARCHAR(MAX) = 'C:\Temp\',
@scriptPS VARCHAR(MAX) = CAST(NEWID() AS VARCHAR(50)) + '.ps1',
@caminho VARCHAR(MAX)
SET @caminho = @diretorio + @scriptPS
EXEC dbo.stpEscreve_Arquivo_FSO
@String = @Ds_Script, -- varchar(max)
@Ds_Arquivo = @caminho -- varchar(1501)
SET @scriptPS = @diretorio + @scriptPS
DECLARE @cmd VARCHAR(4000)
SET @cmd = 'powershell -ExecutionPolicy Unrestricted -File "' + @scriptPS + '"'
DECLARE @Retorno TABLE (Ds_Texto VARCHAR(MAX))
INSERT INTO @Retorno
EXEC master.dbo.xp_cmdshell @cmd
-- Apaga o script gerado
IF (@Fl_Apaga_Script = 1)
BEGIN
EXEC dbo.stpApaga_Arquivo_FSO
@strArquivo = @scriptPS -- varchar(1000)
END
SELECT * FROM @Retorno
END
Usage example:
DECLARE @Script VARCHAR(MAX) = '
$ServerNameList = "VM-DBA"
$OutputFolder = "C:\Teste\Jobs\"
$DoesFolderExist = Test-Path $OutputFolder
$null = if (!$DoesFolderExist){MKDIR "$OutputFolder"}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
foreach ($ServerName in $ServerNameList)
{
Try
{
$objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
Write-Host "Tentando se conectar na instância do servidor $ServerName..." -NoNewline
$objSQLConnection.Open() | Out-Null
Write-Host "Conectado."
$objSQLConnection.Close()
}
Catch
{
Write-Host -BackgroundColor Red -ForegroundColor White "Falha"
$errText = $Error[0].ToString()
if ($errText.Contains("network-related"))
{Write-Host "Erro de conexão à instância. Por favor, verifique o nome do servidor digitado, porta ou firewall."}
Write-Host $errText
continue
}
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
# Arquivo único com todos os jobs
# $srv.JobServer.Jobs | foreach {$_.Script() + "GO`r`n"} | out-file "$OutputFolder\jobs.sql"
# Um arquivo por job
$srv.JobServer.Jobs | foreach-object -process {out-file -filepath $("$OutputFolder\" + $($_.Name -replace "\\", "") + ".sql") -inputobject $_.Script() }
}'
EXEC dbo.stpExecuta_Script_Powershell
@Ds_Script = @Script, -- varchar(max)
@Fl_Apaga_Script = 0 -- bit
Using only PowerShell
If you just want to use PowerShell script manually, below is the complete script.
# Nome da sua máquina
$ServerNameList = "VM-DBA"
# Diretório para salvar os scripts
$OutputFolder = "C:\Jobs\"
$DoesFolderExist = Test-Path $OutputFolder
$null = if (!$DoesFolderExist){MKDIR "$OutputFolder"}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
foreach ($ServerName in $ServerNameList)
{
Try
{
$objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
Write-Host "Tentando se conectar na instância do servidor $ServerName..." -NoNewline
$objSQLConnection.Open() | Out-Null
Write-Host "Conectado."
$objSQLConnection.Close()
}
Catch
{
Write-Host -BackgroundColor Red -ForegroundColor White "Falha"
$errText = $Error[0].ToString()
if ($errText.Contains("network-related"))
{Write-Host "Erro de conexão à instância. Por favor, verifique o nome do servidor digitado, porta ou firewall."}
Write-Host $errText
continue
}
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
# Arquivo único com todos os jobs
# $srv.JobServer.Jobs | foreach {$_.Script() + "GO`r`n"} | out-file "$OutputFolder\jobs.sql"
# Um arquivo por job
$srv.JobServer.Jobs | foreach-object -process {out-file -filepath $("$OutputFolder\" + $($_.Name -replace "\\", "") + ".sql") -inputobject $_.Script() }
}
That's it, folks.
A big hug and see you next time.
SQL Server – How to backup all SQL Agent jobs via command line (CLR C# or Powershell) backup restore sql server agent jobs command line
SQL Server – How to backup all SQL Agent jobs via command line (CLR C# or Powershell) backup restore sql server agent jobs command line





Comentários (0)
Carregando comentários…