Add updated SqlAgent folder
This commit is contained in:
118
SqlAgent/01_Devl/5_PowerShell_Scripts/Execute-RemoteJob.ps1
Normal file
118
SqlAgent/01_Devl/5_PowerShell_Scripts/Execute-RemoteJob.ps1
Normal file
@ -0,0 +1,118 @@
|
||||
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'
|
||||
$SqlServer = 'DOES_DUTAS-SQL1'
|
||||
}
|
||||
'TEST' {
|
||||
$ComputerName = '10.57.110.141'
|
||||
$DatabaseName = 'TestDUTASJobSchedule'
|
||||
$SqlServer = 'DOES_DUTAS-SQL1'
|
||||
}
|
||||
'PROD' {
|
||||
$ComputerName = '10.57.111.120'
|
||||
$DatabaseName = 'ProdDUTASJobSchedule'
|
||||
$SqlServer = 'DOES_DUTAS-SQL'
|
||||
}
|
||||
default {
|
||||
throw "Invalid environment specified: $Env"
|
||||
}
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Remote credentials (consider secure vault in 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 (-not $exitCode) { $exitCode = 1 } # Guard for null/false exit codes
|
||||
|
||||
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=$SqlServer;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 on $SqlServer for job $JobName"
|
||||
}
|
||||
catch {
|
||||
$errorMsg = $_.Exception.Message
|
||||
Write-Host "Failed to log exit code to database $DatabaseName on $SqlServer`: $errorMsg"
|
||||
}
|
||||
```
|
||||
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
140
SqlAgent/01_Devl/5_PowerShell_Scripts/RCSubmit-Job.ps1
Normal file
140
SqlAgent/01_Devl/5_PowerShell_Scripts/RCSubmit-Job.ps1
Normal file
@ -0,0 +1,140 @@
|
||||
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
|
||||
if ($summary.Count -eq 0) {
|
||||
$summary = @($Error[0])
|
||||
}
|
||||
}
|
||||
|
||||
# --- Email Notification Settings ---
|
||||
$smtpServer = "smtp4.dc.gov"
|
||||
$fromEmail = "Dutas@dc.gov"
|
||||
$toEmail = "zarath.lalputan@dc.gov"
|
||||
$ccEmail = @("srujani.chandragiri@dc.gov", "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>
|
||||
"@
|
||||
|
||||
# --- Attachment Setup ---
|
||||
# Automatically attach MSGLOG.txt if it exists in the JOBLOG folder
|
||||
$attachmentPath = Join-Path $syslogFolder "MSGLOG.txt"
|
||||
|
||||
$sendParams = @{
|
||||
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 = $true
|
||||
}
|
||||
|
||||
if (Test-Path $attachmentPath) {
|
||||
$sendParams['Attachments'] = $attachmentPath
|
||||
Write-Host "Attachment found: $attachmentPath" -ForegroundColor Cyan
|
||||
} else {
|
||||
Write-Host "No MSGLOG.txt found at $syslogFolder" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# --- Conditional Email Sending ---
|
||||
# ===================================================================================
|
||||
# EMAIL SEND CONDITION TOGGLE:
|
||||
# By default, email will ALWAYS be sent whether the job succeeded or failed.
|
||||
# To send email ONLY if the job fails, uncomment the next line:
|
||||
# if ($isSuccess -eq 1) {
|
||||
# ===================================================================================
|
||||
|
||||
try {
|
||||
Write-Host "Preparing to send email to $toEmail..." -ForegroundColor Yellow
|
||||
Send-MailMessage @sendParams
|
||||
Write-Host "Email sent successfully to $toEmail" -ForegroundColor Cyan
|
||||
}
|
||||
catch {
|
||||
Write-Host "Failed to send email: $($_.Exception.Message)" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# ===================================================================================
|
||||
# End of email send condition block (only required if you uncomment the IF above)
|
||||
# } # End Email send condition
|
||||
# ===================================================================================
|
||||
|
||||
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