top of page

PowerShell | Service Monitor & Send Email

Windows Services: Ensuring System Security, Stability, and Performance

Monitoring Windows services is a critical aspect of system administration that ensures the health, security, and performance of an IT environment. Here are the key reasons why monitoring Windows services is essential:

1. Ensuring Service Availability and Reliability

Key Points:

  • Critical Services: Many applications and system functions rely on specific services to be running. Monitoring ensures that these services are operational, preventing disruptions in business operations.

  • Minimize Downtime: By continuously monitoring services, administrators can quickly detect and address service failures, minimizing downtime and maintaining system availability.

  • Automatic Recovery: Monitoring can trigger automated actions to restart services or alert administrators, ensuring swift recovery from service interruptions.

​

Example: Monitoring the SQL Server service ensures that database-dependent applications are always available and functioning properly.

​

2. Enhancing System Security

Key Points:

  • Detecting Unauthorized Changes: Continuous monitoring helps detect unauthorized changes to service configurations or unexpected service startups, which could indicate security breaches or malware activity.

  • Service Dependencies: Ensures that essential security services, like antivirus or firewall services, are always running and protecting the system.

  • Compliance: Helps meet regulatory and compliance requirements by ensuring that security-critical services are running as expected.

​

Example: Monitoring the Windows Defender Antivirus Service ensures continuous protection against malware and other threats.

​

3. Improving System Performance and Resource Management

Key Points:

  • Resource Optimization: Ensuring that only necessary services are running helps optimize system resources, such as CPU, memory, and disk usage.

  • Performance Monitoring: Identifying services that consume excessive resources can help in performance tuning and avoiding potential bottlenecks.

  • Efficient Maintenance: Scheduled maintenance and updates can be better managed by knowing the status of all services, avoiding conflicts and ensuring smooth operation.

​

Example: Monitoring resource-intensive services like indexing services can help manage and optimize their impact on system performance.

​

4. Supporting Business Continuity and Disaster Recovery

Key Points:

  • Automated Responses: Monitoring services can trigger automated responses to restart failed services or switch to backup services, supporting business continuity.

  • Disaster Recovery: Ensures that critical services are operational post-recovery, validating the effectiveness of disaster recovery procedures.

  • Historical Data: Collecting historical data on service status can aid in identifying trends and planning for capacity and redundancy requirements.

​

Example: Monitoring the Backup Service ensures that regular backups are completed successfully, providing reliable recovery points in case of data loss.

PowerShell | Service Monitor & Send Email

#===========Pull Computer Exclusion List=========== !! Must Include at Least 1 Entry !! ===

$Exclusion_List = Get-Content C:\Temp\Exclusion.txt

# ==================Pull All Enabled Windows Servers=======================

$Servers = Get-ADComputer -filter { (Operatingsystem -like "Windows Server*" -and Enabled -eq $True) } -Properties * | Select -ExpandProperty Name

#===== Compare the two sources and remove all items matched in the exclusion file list=========

$Exclusions_Remvoed_List = Compare-Object -ReferenceObject $Servers -DifferenceObject $Exclusion_List | ? { $_.SideIndicator -eq '<=' } | Select -ExpandProperty inputobject​

#=========== Start WinRM Test Function =============

Function WinRM-Status($Computers) {

    #Test Path to each system and throttle limit of processes to 256

    $WinRMJob = Invoke-Command -ScriptBlock { Test-Path "C:\" } -ComputerName $Computers  -ThrottleLimit 256 -AsJob | Wait-Job

    #Group the results together, then sort into 2 string arrays with servername only

    $Grouped = $WinRMJob.ChildJobs | Group-Object -Property State

    #Pulls Successful items to one array

    [Array]$WinrmSuccess = ($Grouped | where { $_.Name -eq "Completed" }).Group | % { $_.Location }

    #Pulls Failed Items to another array

    [Array]$noWinrm = Compare-Object -ReferenceObject $Computers -DifferenceObject $WinrmSuccess | Select-Object -ExpandProperty  Inputobject -ErrorAction SilentlyContinue

    #Assigns Array Values

    $properties = @{

        WinRMFails = $noWinrm;

        WinRMPass  = $WinrmSuccess;

    }

    #Create Object and Assign to Var

    $ReturnObj = New-Object -TypeName PSObject -Property $properties

    #Returns the Value

    Return $ReturnObj

}

​

#====================Call Function===================

$Results = WinRM-Status $Exclusions_Remvoed_List

​

#-------------------------Main Command to Be Executed on Remote Systems----------------

$ServiceOnlineChecker = {

    #Loop Through Services to Check Status & Start Serivces

    $ListofServicestoCheck = @('RemoteRegistry', 'WinRM', 'mpssvc')

    $ServiceStatusArray = @()

    Foreach ($serviceA in $ListofServicestoCheck) {

        $ServiceB = Get-Service $serviceA | Select -ExpandProperty Status

        If ($ServiceB.Status -ne "Running") { Start-Service $serviceA -ErrorAction SilentlyContinue }

        Sleep 5

        Get-Service -ComputerName $Env:Computername -name $serviceA | Select MachineName, Displayname, Status

    }                

} # End Main Command

​

#====== Execute Command on List of Servers in $Results.WinRMPass======

$ServiceChecker = @()

$ServiceChecker = invoke-command -ComputerName $Results.WinRMPass -scriptblock $ServiceOnlineChecker -ErrorAction SilentlyContinue

​

#==Filter looking for all services not equal to running=======

$MyData = $ServiceChecker | Where { $_.status.tostring() -ne "Running" } | Select MachineName, Displayname, Status -ErrorAction SilentlyContinue

​

<#======================================================

This MyData Variable will only display services that 

are still not running after an attempt to start 

======================================================#>

$head = "<style>"

$head = $head + "BODY{background-color:white;}"

$head = $head + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"

$head = $head + "TH{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:Yellow}"

$head = $head + "TD{border-width: 1px;padding: 8px;border-style: solid;border-color: black;background-color:white}"

$head = $head + "</style>"

$MyData | ConvertTo-HTML -Head $head -Body $strMail | Out-File "C:\temp\Service_Status.Html"

​

#////////////Send Email Alert\\\\\\\\"

$SmtpServer = "mail.server.com"

$SMTPFrom = "User@Server.com"

$SMTPto = "User@Server.com"

$SMTPSubject = "Service Status Report"

$SMTPBody = "Service Check SCRIPT from server See attached file"

Send-Mailmessage -SmtpServer $SmtpServer -from $SMTPFrom -to $SMTPto -Subject $SMTPSubject -Body $SMTPBody -Attachments "C:\temp\Service_Status.Html"   

PowerShell Windows Output Services
PowerShell Windows Output Services
bottom of page