Blogger Templates

Translate

PowerShell Script to Check SharePoint Timer Job and Mail to User if Fails and Restart the Service

Scenario: when we have failed SharePoint timer job due to windows SharePoint Timer Service where not responded. In this case we need to go and check the timer jobs, if it's failed. go and check windows SharePoint Timer Service ans restart the service. if it happens in one server means, it wont take much time. if its in large farm. It will take much time. so we thought of creating script for it.

What the Script will do:
Script will check the timer job which is failed state for today. if it's has failed job, it will send mail to support team and restart the windows Timer Service.

Script:

Add-PSSnapin Microsoft.sharepoint.powershell

$farm = get-spfarm
$tservice = $farm.TimerService

$a = Get-Date

function sendMail{

     $file = "d:\failedjobs.csv"

     $att = new-object Net.Mail.Attachment($file)

     #SMTP server name
     $smtpServer = "fill the smtpserver"

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure 
     $msg.From = "sharepoint2013@g.com"

    
     $msg.CC.Add("abcdef@g.com")

     $msg.To.Add("abcd@g.com")

     $msg.subject = "Failed Timer Jobs of --- Servers"

     $msg.body = "Hi Team, Please find Attachment of Failed Jobs of ---- Servers"

     $msg.Attachments.Add($att)

     #Sending email 

     $smtp.Send($msg)

     Write-Host "Email Sent"
     
     $att.Dispose()
}
function sendMail1{

          #SMTP server name
      $smtpServer = "fill the smtpserver"

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure 
     $msg.From = "sharepoint2013@g.com"

    
     $msg.CC.Add("abcdef@g.com")

     $msg.To.Add("abcd@g.com")

     $msg.subject = "Failed stopping/Starting SharePoint Timer Service"

     $msg.body = "Hi Team, SharePoint Timer Service not stopped/started in ---- Servers"

     #Sending email 

     $smtp.Send($msg)

     Write-Host "Email Sent"
     
     
}

$fjobs = $tservice.JobHistoryEntries | ?{$_.Status -eq "Failed"} |  Where-Object {$_.StartTime.day -eq $a.day -and $_.StartTime.month -eq $a.month} 

$fjobs | select JobDefinitionTitle,Status,ServerName,StartTime,EndTime,ErrorMessage |Export-Csv -Delimiter ',' -Path D:\failedjobs.csv 

foreach($j in $fjobs)
{
$tj= $j
}

if($tj.Status -eq "Failed")
{

    sendMail
    $sts = Get-Service -DisplayName "SharePoint Timer Service"
    net stop $sts

    $sts.WaitForStatus('Stopped','00:00:05')

    if ($sts.Status -ne 'Stopped')
    {
        sendMail1
    }
    else
    {
        net start $sts
    }

}
else
{
Write-Host " No failed Jobs Today"
}


Note: I hope, It will help who have same kind of scenario.