Add SQLAgent folder
This commit is contained in:
@ -0,0 +1,16 @@
|
||||
# Example PowerShell snippet
|
||||
$Server = "DOES-DUTAS-SQL1"
|
||||
$BackupPath = "\\DOES-RAINVM-DEV\E$\Neeraj\SqlAgent\Backup\"
|
||||
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
|
||||
$ZipFile = "$BackupPath\SQLAgentJobs_$Timestamp.zip"
|
||||
|
||||
# Make backup folder if not exist
|
||||
if (-not (Test-Path $BackupPath)) { New-Item -ItemType Directory -Path $BackupPath }
|
||||
|
||||
# Export all jobs as SQL files
|
||||
sqlcmd -S $Server -Q "EXEC msdb.dbo.sp_help_job" -o "$BackupPath\SQLAgentJobs_$Timestamp.txt"
|
||||
|
||||
# Compress to zip
|
||||
Compress-Archive -Path "$BackupPath\*" -DestinationPath $ZipFile -Force
|
||||
|
||||
Write-Host "✅ Backup complete: $ZipFile"
|
||||
102
SQLAgent/01_Devl/4_PowerShell_Scripts/Execute-RemoteJob.ps1
Normal file
102
SQLAgent/01_Devl/4_PowerShell_Scripts/Execute-RemoteJob.ps1
Normal file
@ -0,0 +1,102 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$JobName,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('DEVL', 'TEST', 'PROD')]
|
||||
[string]$Env
|
||||
)
|
||||
|
||||
try {
|
||||
Write-Host "Starting job $JobName in environment $Env at $(Get-Date)"
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Extract JCL from JobName (ENV_FREQUENCY_JOB pattern)
|
||||
# ------------------------------------------------------------
|
||||
$JCL = $JobName -replace '^[A-Z]+_[A-Z]+_', ''
|
||||
Write-Host "Extracted JCL: $JCL from JobName: $JobName" -ForegroundColor Yellow
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Environment-specific configuration
|
||||
# ------------------------------------------------------------
|
||||
switch ($Env.ToUpper()) {
|
||||
'DEVL' {
|
||||
$ComputerName = '10.57.110.120'
|
||||
$DatabaseName = 'DevlDUTASJobSchedule'
|
||||
}
|
||||
'TEST' {
|
||||
$ComputerName = '10.57.110.141'
|
||||
$DatabaseName = 'TestDUTASJobSchedule'
|
||||
}
|
||||
'PROD' {
|
||||
$ComputerName = '10.57.111.120'
|
||||
$DatabaseName = 'ProdDUTASJobSchedule'
|
||||
}
|
||||
default {
|
||||
throw "Invalid environment specified: $Env"
|
||||
}
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Remote credentials
|
||||
# (recommend moving credentials to secure vault for production)
|
||||
# ------------------------------------------------------------
|
||||
$username = "DUTASSQLAdminP@does.dcgov.priv"
|
||||
$password = "4ho@3Pr&Xof8" | ConvertTo-SecureString -AsPlainText -Force
|
||||
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Execute job remotely using the extracted JCL
|
||||
# ------------------------------------------------------------
|
||||
Write-Host "Connecting to remote server $ComputerName ..."
|
||||
$exitCode = Invoke-Command -ComputerName $ComputerName `
|
||||
-Credential $credential `
|
||||
-Authentication CredSSP `
|
||||
-SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck) `
|
||||
-ArgumentList $JobName, $JCL, $Env `
|
||||
-ScriptBlock {
|
||||
param($JobName, $JCL, $Env)
|
||||
|
||||
Write-Host "Remote execution - JobName: $JobName, JCL: $JCL, Env: $Env"
|
||||
|
||||
$process = Start-Process -FilePath "powershell.exe" `
|
||||
-ArgumentList "-ExecutionPolicy Bypass -File `"E:\PSScript\RCSubmit-Job.ps1`" -JobName `"$JCL`" -Env `"$Env`"" `
|
||||
-NoNewWindow -Wait -PassThru
|
||||
return $process.ExitCode
|
||||
}
|
||||
|
||||
if ($exitCode -eq 0) {
|
||||
Write-Host "Job $JobName (JCL: $JCL) completed successfully at $(Get-Date)" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Error "Job $JobName (JCL: $JCL) failed with exit code: $exitCode"
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Error "Job $JobName failed with error: $($_.Exception.Message)"
|
||||
$exitCode = 1
|
||||
}
|
||||
finally {
|
||||
# ------------------------------------------------------------
|
||||
# Log exit code to the appropriate database
|
||||
# ------------------------------------------------------------
|
||||
try {
|
||||
$connectionString = "Server=localhost;Database=$DatabaseName;Trusted_Connection=true;"
|
||||
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||
$connection.Open()
|
||||
|
||||
$command = $connection.CreateCommand()
|
||||
$command.CommandText = @"
|
||||
INSERT INTO dbo.JobExitCodes (JobName, RunDate, ExitCode, RecordedTime)
|
||||
VALUES ('$JobName', CAST(GETDATE() AS DATE), $exitCode, GETDATE());
|
||||
"@
|
||||
$command.ExecuteNonQuery()
|
||||
$connection.Close()
|
||||
Write-Host "Exit code $exitCode logged to database $DatabaseName for job $JobName"
|
||||
}
|
||||
catch {
|
||||
$errorMsg = $_.Exception.Message
|
||||
Write-Host "Failed to log exit code to database $DatabaseName`: $errorMsg"
|
||||
}
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
108
SQLAgent/01_Devl/4_PowerShell_Scripts/RCSubmit-Job.ps1
Normal file
108
SQLAgent/01_Devl/4_PowerShell_Scripts/RCSubmit-Job.ps1
Normal file
@ -0,0 +1,108 @@
|
||||
param(
|
||||
[string]$JobName,
|
||||
[string]$Env
|
||||
)
|
||||
|
||||
# --- Parameter Validation ---
|
||||
if (-not $JobName) {
|
||||
Write-Host "JobName parameter is required" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if (-not $Env) {
|
||||
Write-Host "Environment (Env) parameter is required" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Execute Job ---
|
||||
Write-Host "Submitting job: $JobName in environment: $Env" -ForegroundColor Cyan
|
||||
$output = & "$env:rcbin\submit.exe" -DSN="DOESTAX.$Env.JOBS.BATCH.LIB($JobName)"
|
||||
$exitCode = [int]$LASTEXITCODE
|
||||
$isSuccess = 0
|
||||
|
||||
# --- Parse SYSLOG Path ---
|
||||
$syslogPath = $null
|
||||
$syslogFolder = "Not found"
|
||||
$content = @()
|
||||
$summary = @()
|
||||
|
||||
try {
|
||||
$syslogPath = $output | Select-String -Pattern "SYSLOG=\[(.*)\]" | ForEach-Object { $_.Matches.Groups[1].Value }
|
||||
|
||||
if ($syslogPath -and (Test-Path $syslogPath)) {
|
||||
$syslogFolder = Split-Path $syslogPath -Parent
|
||||
$content = Get-Content $syslogPath -ErrorAction Stop
|
||||
$summary = $content | Select-String -Pattern "%Job Overall Stats:" -Context 0,7 | ForEach-Object {
|
||||
$_.Context.PostContext | Select-Object -Skip 1 -First 5
|
||||
}
|
||||
} else {
|
||||
Write-Host "SYSLOG path not found or inaccessible: $syslogPath" -ForegroundColor Yellow
|
||||
$summary = @("SYSLOG file not found in output", "Raw output:", $output -join "`n")
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Host "Error processing SYSLOG: $($_.Exception.Message)" -ForegroundColor Yellow
|
||||
$summary = @("Error reading SYSLOG: $($_.Exception.Message)", "Raw output:", $output -join "`n")
|
||||
}
|
||||
|
||||
# --- Evaluate Return Codes ---
|
||||
$successConditions = @(
|
||||
{ $JobName -eq "GSIRQ300" -and $exitCode -eq 50 },
|
||||
{ $JobName -eq "DTSGWAGE" -and $exitCode -eq 8 },
|
||||
{ $JobName -eq "DTSGCHKS" -and $exitCode -eq 8 },
|
||||
{ $JobName -eq "DTSGPAYT" -and $exitCode -eq 8 },
|
||||
{ $JobName -eq "DTSBXACH" -and $exitCode -eq 2 },
|
||||
{ $JobName -eq "DTSBXREL" -and $exitCode -eq 2 },
|
||||
{ $JobName -eq "DTSMIN02" -and $exitCode -eq 4 },
|
||||
{ $JobName -eq "DTSBE405" -and $exitCode -eq 910 },
|
||||
{ $JobName -eq "DTSBXREJ" -and $exitCode -eq 4 },
|
||||
{ $JobName -eq "DTSRQ444" -and $exitCode -eq 4 },
|
||||
{ $exitCode -eq 0 }
|
||||
)
|
||||
|
||||
if ($successConditions | Where-Object { & $_ }) {
|
||||
Write-Host "Job $JobName succeeded with code $exitCode" -ForegroundColor Green
|
||||
$isSuccess = 0
|
||||
} else {
|
||||
Write-Host "Job $JobName failed with code $exitCode" -ForegroundColor Red
|
||||
$isSuccess = 1
|
||||
# Only use error if we don't have a proper summary
|
||||
if ($summary.Count -eq 0) {
|
||||
$summary = @($Error[0])
|
||||
}
|
||||
}
|
||||
|
||||
# --- Email Notification ---
|
||||
$smtpServer = "smtp4.dc.gov"
|
||||
$fromEmail = "Dutas@dc.gov"
|
||||
$toEmail = "neerajk@innovaconsulting.com"
|
||||
$ccEmail = @("neerajk@innovaconsulting.com")
|
||||
|
||||
$emailBody = @"
|
||||
<pre style='font-family: Courier, monospace;'>
|
||||
DUTAS Batch Job: $JobName Execution Report
|
||||
==========================================
|
||||
$($summary -join "`n")
|
||||
==========================================
|
||||
|
||||
Return Code: $exitCode
|
||||
Status: $(if ($isSuccess -eq 0) { "SUCCESS" } else { "FAILED" })
|
||||
JOBLOG Path: $syslogFolder
|
||||
</pre>
|
||||
"@
|
||||
|
||||
try {
|
||||
Send-MailMessage -SmtpServer $smtpServer -Port 25 `
|
||||
-From $fromEmail -To $toEmail -Cc $ccEmail `
|
||||
-Subject "DUTAS-[$Env] Job Status: $JobName - $(if ($isSuccess -eq 0) { 'SUCCESS' } else { 'FAILED' })" `
|
||||
-Body $emailBody -BodyAsHtml
|
||||
Write-Host "Email sent successfully to $toEmail" -ForegroundColor Cyan
|
||||
}
|
||||
catch {
|
||||
Write-Host "Failed to send email: $($_.Exception.Message)" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host "`n---------------------------------------------"
|
||||
Write-Host "Job: $JobName | ExitCode: $exitCode | Status: $(if ($isSuccess -eq 0) { 'SUCCESS' } else { 'FAILED' })"
|
||||
Write-Host "---------------------------------------------`n"
|
||||
|
||||
exit $isSuccess
|
||||
Reference in New Issue
Block a user