SQL Agen Scheduler - Updated

This commit is contained in:
Neeraj Kumar
2025-10-20 07:54:46 -04:00
parent 42a3da46ab
commit f8c32748c5
136 changed files with 5836 additions and 1216 deletions

View 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