Tuesday, 17 June 2025

SQLDBA- Poweshell, get the alerts if the service is stopped

 



# Define the service name and email parameters

$serviceName = "Service name" -- Keep service name  here 

$smtpServer = "smtp.gmai.com"

$smtpFrom = "ksubbareddy.sap@gmail.com"

$smtpTo = "ksubbareddy.sap@gmail.com"

#$smtpSubject = "$serviceName service status on SQL1 Server"

$smtpBody = ""


# Get the hostname of the current server

$hostname = $env:COMPUTERNAME


# Function to send HTML email

function Send-Email {

    param (

        [string]$smtpServer,

        [string]$smtpFrom,

        [string]$smtpTo,

        [string]$smtpSubject,

        [string]$smtpBody

    )

    Send-MailMessage -SmtpServer $smtpServer -From $smtpFrom -To $smtpTo -Subject $smtpSubject -Body $smtpBody -BodyAsHtml

}


# Check the service status

try {

    $service = Get-Service -Name $serviceName -ErrorAction Stop


    if ($service.Status -eq 'Stopped') {

        $smtpSubject = " X!! [ALERT] $serviceName is STOPPED on $hostname"

        $smtpBody = @"

        <html>

        <body>

            <h2 style='color:red;'>ALERT: $serviceName is STOPPED!</h2>

            <p>The service <strong>$serviceName</strong> is currently <span style='color:red;'>stopped</span> on the server <strong>$hostname</strong>.</p>

        </body>

        </html>

"@

        Write-Host "ALERT: $serviceName is STOPPED on $hostname!" -ForegroundColor Red

    }

    else {

        $smtpSubject = "[OK] $serviceName is RUNNING on $hostname"

        $smtpBody = @"

        <html>

        <body>

            <h2 style='color:green;'>$serviceName is Running</h2>

            <p>The service <strong>$serviceName</strong> is currently <span style='color:green;'>running</span> on the server <strong>$hostname</strong>.</p>

        </body>

        </html>

"@

        Write-Host "$serviceName is running on $hostname." -ForegroundColor Green

    }


    # Send the email notification

    Send-Email -smtpServer $smtpServer -smtpFrom $smtpFrom -smtpTo $smtpTo -smtpSubject $smtpSubject -smtpBody $smtpBody

    Write-Host "Email notification sent." -ForegroundColor Cyan

}

catch {

    Write-Host "ERROR: Could not find or check the service '$serviceName' on $hostname." -ForegroundColor Yellow

    Write-Host $_.Exception.Message -ForegroundColor DarkYellow

}


 


 

No comments:

Post a Comment

SQLDBA - Get Space Used by Tables and Indexes in SQL Server

 Get Space Used by Tables and Indexes in SQL Server Databases can consume significant amounts of storage, so it’s important to understand ho...