Skip to main content

PowerShell: Restart Service and Email Windows Logs

01 February, 2021
This video demonstrates how to write a simple script that checks if a service is running. If it is not running, it will start the service, capture windows logs, and then email those logs to a defined email address.

PowerShell Script:

####UN-ZIP#####
##Script to verify alfrescoApache running if not reboot

function FuncCheckService{
     param($ServiceName)
     
     $arrService = Get-Service -Name $ServiceName
     if ($arrService.Status -eq "Running"){
        $status = $true
     } else {
        $status = $false
     }
     return $status
}

function FuncStartService{
     param($ServiceName)
     $arrService = Get-Service -Name $ServiceName
         if ($arrService.Status -ne "Running"){
         Start-Service $ServiceName
         Write-Output "Starting " $ServiceName " service" 
         " ---------------------- " 
         " Service is now started"
     } 
     if ($arrService.Status -eq "running"){ 
        Write-Output "$ServiceName service is already started"
     }
 }

 function GetLogs{
    param(
        [Parameter(Position = 0, Mandatory = $true)]
        [string] $start,

        [Parameter(Position = 1, Mandatory = $true)]
        [string] $end

    )
     
    $EventLog = 'Application', 'System', 'Security'

    ## The output file path of the text file that contains all matching events
    $OutputFilePath = 'J:\Temp\eventlogs.txt'

    ## Create the Where filter ahead of time to only get events within the timeframe
    $filter = {($_.TimeCreated -ge $start) -and ($_.TimeCreated -le $end)}

    $op_logs = Get-WinEvent -ListLog * -ComputerName 'localhost' | Where {$_.RecordCount -and ($EventLog -contains $_.LogName)}

    $i = 0
    foreach ($op_log in $op_logs) {
        Write-Progress -Activity "Processing event logs" -status "Processing $($op_log.LogName) event log" -percentComplete ($i / $op_logs.count*100)
        #Get-WinEvent $op_log.LogName -ComputerName $c | Where $filter |
        Get-EventLog -Log $op_log.LogName -After $starttime -Before $endtime 
            Select @{n='Time';e={$_.TimeCreated}},
                @{n='Source';e={$_.ProviderName}},
                @{n='EventId';e={$_.Id}},
                @{n='Message';e={$_.Message}},
                @{n='EventLog';e={$_.LogName}} | Out-File -FilePath $OutputFilePath -Append -Force
         $i++
    }
 }

 function SendEmail{
    $smtpServer = "mail.server.com"
    $smtpPort = 587
    $smtpUsername = "***"
    $smtpPassword = "***"

    $from = "**"
    $to = "**"
    $subject = "Service has failed"
    $body = "Attached are the logs 5 min before service failed."

    $attachmentPath = "C:\Temp\EventLogs.txt"

    $smtpCredentials = New-Object System.Management.Automation.PSCredential ($smtpUsername, (ConvertTo-SecureString -String $smtpPassword -AsPlainText -Force))

    Send-MailMessage -SmtpServer $smtpServer -Port $smtpPort -Credential $smtpCredentials -From $from -To $to -Subject $subject -Body $body -Attachments $attachmentPath
 }

 $srvcs = 'Spooler'
#Wait 1 minute
Start-Sleep -Seconds 60

# Get Current Time
$endtime = Get-Date -format "MM-dd-yyyy HH:mm:ss"
$starttime = ((Get-Date).AddMinutes(-5) ).ToString("MM-dd-yyyy HH:mm:ss")

foreach ($svc in $srvcs){
    $started = FuncCheckService $svc
    if (!$started) {
        FuncStartService $svc
        GetLogs $starttime $endtime
        SendEmail 
    }
}