46 lines
1.5 KiB
PowerShell
46 lines
1.5 KiB
PowerShell
<#
|
|
.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-SQL" -Env "PROD"
|
|
#>
|
|
|
|
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
|