SQL Agen Scheduler - Updated
This commit is contained in:
BIN
SQLAgent/01_Devl/6_Backup_Restore/Backup-Restore-Guide.docx
Normal file
BIN
SQLAgent/01_Devl/6_Backup_Restore/Backup-Restore-Guide.docx
Normal file
Binary file not shown.
48
SQLAgent/01_Devl/6_Backup_Restore/Backup-SQLAgent.ps1
Normal file
48
SQLAgent/01_Devl/6_Backup_Restore/Backup-SQLAgent.ps1
Normal file
@ -0,0 +1,48 @@
|
||||
# ===================================================================
|
||||
# SQL Agent Jobs Backup Script (PowerShell)
|
||||
# Modern Version using SqlServer module
|
||||
# & "E:\Neeraj\SqlAgent\v2\01_Devl\6_Backup\Backup-SQLAgent.ps1" `
|
||||
# -ServerName "DOES-DUTAS-SQL1" `
|
||||
# -BackupPath "\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Backup\"
|
||||
#
|
||||
# ===================================================================
|
||||
|
||||
param (
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ServerName,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$BackupPath
|
||||
)
|
||||
|
||||
# Load SQL Server PowerShell module
|
||||
Import-Module SqlServer -ErrorAction Stop
|
||||
|
||||
# Create timestamp and output paths
|
||||
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
|
||||
$ZipFile = Join-Path $BackupPath "SQLAgentJobs_$Timestamp.zip"
|
||||
|
||||
# Ensure backup folder exists
|
||||
if (-not (Test-Path $BackupPath)) {
|
||||
New-Item -ItemType Directory -Path $BackupPath | Out-Null
|
||||
}
|
||||
|
||||
# Connect to SQL Server
|
||||
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $ServerName
|
||||
|
||||
# Export all jobs as individual SQL scripts
|
||||
$JobFiles = @()
|
||||
foreach ($job in $server.JobServer.Jobs) {
|
||||
$SafeJobName = ($job.Name -replace '[\\/:*?"<>|]', '_')
|
||||
$FileName = Join-Path $BackupPath "$SafeJobName`_$Timestamp.sql"
|
||||
$job.Script() | Out-File -FilePath $FileName -Encoding UTF8
|
||||
$JobFiles += $FileName
|
||||
}
|
||||
|
||||
# Compress all SQL files into a single ZIP
|
||||
Compress-Archive -Path $JobFiles -DestinationPath $ZipFile -Force
|
||||
|
||||
# Optional: clean up individual .sql files
|
||||
# Remove-Item -Path $JobFiles
|
||||
|
||||
Write-Host "SQL Agent jobs backup complete: $ZipFile" -ForegroundColor Green
|
||||
19
SQLAgent/01_Devl/6_Backup_Restore/BackupDB.sql
Normal file
19
SQLAgent/01_Devl/6_Backup_Restore/BackupDB.sql
Normal file
@ -0,0 +1,19 @@
|
||||
USE master;
|
||||
GO
|
||||
|
||||
DECLARE @SrcDB NVARCHAR(128) = 'DevlDUTASJobSchedule';
|
||||
DECLARE @BackupPath NVARCHAR(260) = '\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Backup\' + @SrcDB + '.bak';
|
||||
DECLARE @SQL NVARCHAR(MAX);
|
||||
|
||||
-- Dynamic SQL for backup
|
||||
SET @SQL = '
|
||||
BACKUP DATABASE [' + @SrcDB + ']
|
||||
TO DISK = N''' + @BackupPath + '''
|
||||
WITH INIT, COMPRESSION, STATS = 10;
|
||||
';
|
||||
|
||||
-- Execute backup
|
||||
EXEC(@SQL);
|
||||
|
||||
PRINT 'Backup completed: ' + @BackupPath;
|
||||
GO
|
||||
45
SQLAgent/01_Devl/6_Backup_Restore/Cleanup-SQLAgent.ps1
Normal file
45
SQLAgent/01_Devl/6_Backup_Restore/Cleanup-SQLAgent.ps1
Normal file
@ -0,0 +1,45 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Deletes SQL Agent jobs whose names start with a given environment prefix (e.g., DEVL, TEST, PROD).
|
||||
|
||||
.PARAMETER ServerName
|
||||
SQL Server instance name (use FCI virtual name if clustered).
|
||||
|
||||
.PARAMETER Env
|
||||
Environment prefix for job deletion (e.g., DEVL, TEST, PROD).
|
||||
|
||||
.EXAMPLE
|
||||
.\Cleanup-SQLAgent.ps1 -ServerName "DOES-DUTAS-SQL1" -Env "DEVL"
|
||||
#>
|
||||
|
||||
param (
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ServerName,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Environment
|
||||
)
|
||||
|
||||
# Load SQL Server module
|
||||
Import-Module SqlServer -ErrorAction Stop
|
||||
|
||||
# Connect to SQL Server
|
||||
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $ServerName
|
||||
|
||||
# Create log file path (same folder as script)
|
||||
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||
$LogPath = Join-Path $ScriptRoot "CleanupSQLAgent_$($Environment)_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||
|
||||
"=== SQL Agent Cleanup Started for $Environment : $(Get-Date) ===" | Out-File $LogPath -Encoding UTF8
|
||||
|
||||
# Take a snapshot of all jobs first (avoids collection modification issue)
|
||||
$jobsToDelete = @($server.JobServer.Jobs | Where-Object { $_.Name -like "$Environment*" })
|
||||
|
||||
foreach ($job in $jobsToDelete) {
|
||||
Write-Host "Deleting job: $($job.Name)" -ForegroundColor Yellow
|
||||
"Deleting job: $($job.Name)" | Out-File $LogPath -Append -Encoding UTF8
|
||||
$job.Drop()
|
||||
}
|
||||
|
||||
"=== Cleanup Complete for $Environment : $(Get-Date) ===" | Out-File $LogPath -Append -Encoding UTF8
|
||||
Write-Host "All $Environment SQL Agent jobs deleted successfully." -ForegroundColor Green
|
||||
27
SQLAgent/01_Devl/6_Backup_Restore/CleanupSQLAgent.sql
Normal file
27
SQLAgent/01_Devl/6_Backup_Restore/CleanupSQLAgent.sql
Normal file
@ -0,0 +1,27 @@
|
||||
USE msdb;
|
||||
GO
|
||||
|
||||
DECLARE @EnvPrefix NVARCHAR(50) = N'DEVL'; -- <<< Change this to your environment prefix
|
||||
DECLARE @job_id UNIQUEIDENTIFIER;
|
||||
DECLARE @job_name NVARCHAR(200);
|
||||
|
||||
DECLARE JobCursor CURSOR FOR
|
||||
SELECT job_id, name
|
||||
FROM msdb.dbo.sysjobs
|
||||
WHERE name LIKE @EnvPrefix + '%'; -- Only jobs starting with the given prefix
|
||||
|
||||
OPEN JobCursor;
|
||||
FETCH NEXT FROM JobCursor INTO @job_id, @job_name;
|
||||
|
||||
WHILE @@FETCH_STATUS = 0
|
||||
BEGIN
|
||||
PRINT 'Deleting job: ' + @job_name;
|
||||
EXEC msdb.dbo.sp_delete_job @job_id = @job_id;
|
||||
FETCH NEXT FROM JobCursor INTO @job_id, @job_name;
|
||||
END
|
||||
|
||||
CLOSE JobCursor;
|
||||
DEALLOCATE JobCursor;
|
||||
|
||||
PRINT 'All SQL Agent jobs starting with prefix ' + @EnvPrefix + ' deleted successfully.';
|
||||
GO
|
||||
@ -0,0 +1,8 @@
|
||||
$BackupZip = "\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Backup\SQLAgentJobs_20251018_153000.zip"
|
||||
$ExtractPath = "\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Restore\"
|
||||
|
||||
# Create folder if not exist
|
||||
if (-not (Test-Path $ExtractPath)) { New-Item -ItemType Directory -Path $ExtractPath | Out-Null }
|
||||
|
||||
# Extract the ZIP
|
||||
Expand-Archive -Path $BackupZip -DestinationPath $ExtractPath -Force
|
||||
31
SQLAgent/01_Devl/6_Backup_Restore/RestoreDB.sql
Normal file
31
SQLAgent/01_Devl/6_Backup_Restore/RestoreDB.sql
Normal file
@ -0,0 +1,31 @@
|
||||
USE master;
|
||||
GO
|
||||
|
||||
DECLARE @SrcDB NVARCHAR(128) = 'DevlDUTASJobSchedule'; -- original database
|
||||
DECLARE @NewDB NVARCHAR(128) = 'DevlDUTASJobSchedule'; -- database name to restore as
|
||||
DECLARE @BackupPath NVARCHAR(260) = '\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Backup\' + @SrcDB + '.bak';
|
||||
DECLARE @SQL NVARCHAR(MAX);
|
||||
|
||||
-- Optional: check logical file names inside backup
|
||||
-- RESTORE FILELISTONLY FROM DISK = @BackupPath;
|
||||
|
||||
-- Dynamic SQL for restore
|
||||
SET @SQL = '
|
||||
-- Optional: disconnect active connections
|
||||
ALTER DATABASE [' + @NewDB + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
|
||||
|
||||
RESTORE DATABASE [' + @NewDB + ']
|
||||
FROM DISK = N''' + @BackupPath + '''
|
||||
WITH MOVE N''' + @SrcDB + ''' TO N''\\DOES-RAINVM-DEV\E$\SQLData\' + @NewDB + '.mdf'',
|
||||
MOVE N''' + @SrcDB + '_log'' TO N''\\DOES-RAINVM-DEV\E$\SQLLogs\' + @NewDB + '_log.ldf'',
|
||||
REPLACE, STATS = 10;
|
||||
|
||||
-- Set database back to multi-user
|
||||
ALTER DATABASE [' + @NewDB + '] SET MULTI_USER;
|
||||
';
|
||||
|
||||
-- Execute restore
|
||||
EXEC(@SQL);
|
||||
|
||||
PRINT 'Database restored successfully as ' + @NewDB;
|
||||
GO
|
||||
12
SQLAgent/01_Devl/6_Backup_Restore/RestoreSQLAgent.sql
Normal file
12
SQLAgent/01_Devl/6_Backup_Restore/RestoreSQLAgent.sql
Normal file
@ -0,0 +1,12 @@
|
||||
# Connect to SQL Server
|
||||
$ServerName = "DOES-DUTAS-SQL1"
|
||||
$SqlInstance = "localhost" # or server instance name
|
||||
|
||||
# Execute each script
|
||||
$ScriptFiles = Get-ChildItem -Path $ExtractPath -Filter *.sql
|
||||
foreach ($file in $ScriptFiles) {
|
||||
Write-Host "Restoring job from: $($file.FullName)"
|
||||
sqlcmd -S $SqlInstance -i $file.FullName
|
||||
}
|
||||
|
||||
Write-Host "All SQL Agent jobs restored successfully."
|
||||
Reference in New Issue
Block a user