Wednesday, August 26, 2015

PowerShell script to get Site Collection Hits

Hi,

In SharePoint 2013,we can see the Monthly Site Collection Hits under Popularity trends as below
Now our requirement is

To get the total site collection hits of preceding month and trigger the email to our customer regarding the same.
For this we have written the PowerShell script as below

if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PSSnapin Microsoft.SharePoint.Powershell
}
#Global Variables
$site=Get-SPSite "siteurl"
$web=get-SPWeb "weburl"
$fromaddress = "abc@domain.com"
$toaddress = "xyz@domain.com"
$ccaddress = “efg@domain.com”

$date = get-date
        $numdays = $date.Day
        $ed = $date.AddDays(-$numdays)
        $numdays = $ed.Day
        $sd = $ed.AddDays( -$numdays + 1)
        $sd = ((($sd.AddHours(0-$sd.hour)).AddMinutes(0-$sd.Minute)).AddSeconds(0-$sd.Second)).AddMilliseconds(0-$sd.millisecond)
        $ed = $ed.AddDays(1)
        $ed = ((($ed.AddHours(0-$ed.hour)).AddMinutes(0-$ed.Minute)).AddSeconds(0-$ed.Second)).AddMilliseconds(0-$ed.millisecond)


#EndRegion Global Variables

#Region Site Collection Hits
$SSP = Get-SPEnterpriseSearchServiceApplication

$Filterdate = (Get-Date).AddDays(-1)
$AnalyticsResult = $SSP.GetRollupAnalyticsItemData(1,[System.Guid]::Empty,$site.ID,$web.ID)

#EndRegion Site Collection Hits

#############Email for Site Collection Hits ####################################
$Subject = "Site Collection Hits for the Month of -" + $sd.Date.Date.ToString("MMM")+$sd.Date.Date.ToString("yy")
$body = "--------------------------------------------------------------------------------------------"<br>Site Collection Hits are - "+$AnalyticsResult.GetHitCountForMonth($Filterdate) +"<br> -------------------------------------------------------------------------------------------------"
$attachment = $filename
#SMTP IP Address of Production
$smtpserver = "IP Address"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.To.Add($ccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
$message.Dispose()
$smtp.Dispose()
$salestoolsadditionsfile.Delete()
#######################################################

Finally email has been triggered without put as below

No comments:

Post a Comment