Added latest changes for SQL Agent - Refer v2

This commit is contained in:
Neeraj Kumar
2025-10-20 08:03:45 -04:00
parent 716014d0bf
commit 49a18b5c47
225 changed files with 10452 additions and 0 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