Wednesday, 13 September 2017

Get site usage using powershell

# ====================================================================================
# SitesUsage.ps1 - Export 'LastItemModifiedDate' property of each site in a csv file
# ====================================================================================

param(
[Parameter(Mandatory=$False)]
  [bool]$displayMessages = $true,
[Parameter(Mandatory=$False)]
  [string]$SMTPServer="",
[Parameter(Mandatory=$False)]
  [string]$ToEmailAddress="",
[Parameter(Mandatory=$False)]
  [string]$FromEmailAddress="",
[Parameter(Mandatory=$False)]
  [string]$delimiter=","
)

# Applies Read Access to the specified accounts for a web application
Function Add-UserPolicy([String]$url)
{
    Try
    {
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup("$url")
$user = ([Security.Principal.WindowsIdentity]::GetCurrent()).Name
$displayName = "Sites Usage Read Account"
$perm = "Full Read"

# If the web app is not Central Administration
If ($webapp.IsAdministrationWebApplication -eq $false)
{
# If the web app is using Claims auth, change the user accounts to the proper syntax
If ($webapp.UseClaimsAuthentication -eq $true)
{$user = 'i:0#.w|'+$user}
[Microsoft.SharePoint.Administration.SPPolicyCollection]$policies = $webapp.Policies
[Microsoft.SharePoint.Administration.SPPolicy]$policy = $policies.Add($user, $displayName)
[Microsoft.SharePoint.Administration.SPPolicyRole]$policyRole = $webapp.PolicyRoles | where {$_.Name -eq $perm}
If ($policyRole -ne $null)
{$policy.PolicyRoleBindings.Add($policyRole)}
$webapp.Update()
If($displayMessages)
{Write-Host -ForegroundColor White " Read access applied for `"$user`" account to `"$url`""}
}
    }
    Catch
    {
        $_
        Write-Warning "An error occurred applying Read access for `"$user`" account to `"$url`""
    }
}

# Load assemblies
Function Load-Assemblies
{
Try
{
If ((Get-PsSnapin |?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null)
   {
If($displayMessages)
{
       Write-Host -ForegroundColor Green "-----------------------------------------"
       Write-Host -ForegroundColor Green " - Loading SharePoint Powershell Snapin -"
       Write-Host -ForegroundColor Green "-----------------------------------------"
}
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop | Out-Null
   }
}
Catch
{
If($displayMessages)
{
Write-Host -ForegroundColor Green "------------------------------------------"
Write-Host -ForegroundColor Green " - Loading Microsoft.SharePoint Assembly -"
Write-Host -ForegroundColor Green "------------------------------------------"
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null
}
}

# Send Email with log file as attachment
Function SendEmail($attachment)
{
Try
{
If($displayMessages)
{
Write-Host -ForegroundColor White "--------------------------------------------------------------"
Write-Host -ForegroundColor White " Sending Email to $ToEmailAddress with $attachment in attachment."
}
Send-MailMessage -To $ToEmailAddress -From $FromEmailAddress -Subject "Sites Usage - $env:COMPUTERNAME" -SmtpServer $SMTPServer -Attachments $attachment

If($displayMessages)
{Write-Host -ForegroundColor Green " Email sent successfully to $ToEmailAddress"}
}
Catch
{Write-Warning $_}
}

$DateStarted = $(Get-date)

If($displayMessages)
{
Write-Host -ForegroundColor Green "----------------------------------"
Write-Host -ForegroundColor Green "- Script started on $DateStarted -"
Write-Host -ForegroundColor Green "----------------------------------"
}
# Check Permission Level
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{Write-Warning "You don't have Administrator rights to run this script."}
else
{
If($SMTPServer)
{
If (!$ToEmailAddress -or !$FromEmailAddress)
{
Write-Warning "Please specify a 'ToEmailAddress' and a 'FromEmailAddress' parameter."
Exit
}
}
# Load assemblies
Load-Assemblies

# Local variables
$sitesList = $null
$sitesList = @()

# Build structure
$itemStructure = New-Object psobject
$itemStructure | Add-Member -MemberType NoteProperty -Name "Title" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "URL" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "Template" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "Year" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "Month" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "Day" -value ""
$itemStructure | Add-Member -MemberType NoteProperty -Name "LastModifiedDate" -value ""

If($displayMessages)
{
Write-Host -ForegroundColor Green "-----------------------"
Write-Host -ForegroundColor Green " - Scanning All Sites -"
Write-Host -ForegroundColor Green "-----------------------"
}

# Browse sites
$WebSrv = [microsoft.sharepoint.administration.spwebservice]::ContentService
foreach ($webApp in $WebSrv.WebApplications)
{
foreach ($AltUrl in $webapp.AlternateUrls)
{Add-UserPolicy $AltUrl.uri}

foreach ($site in $WebApp.sites)
{
foreach($web in $site.AllWebs)
{
# Build structure
$siteInfos = $itemStructure | Select-Object *;

$siteInfos.Title = $web.Title;
$siteInfos.URL = $web.Url;
$siteInfos.Template = $web.WebTemplate;

$LastModifiedDate = Get-Date -Date $web.LastItemModifiedDate
$siteInfos.Year = $LastModifiedDate.Year;
$siteInfos.Month = $LastModifiedDate.Month;
$siteInfos.Day = $LastModifiedDate.Day;
$siteInfos.LastModifiedDate = $web.LastItemModifiedDate.ToString('d');

$sitesList += $siteInfos;
}
}
}

# CSV Export
If($displayMessages)
{
Write-Host -ForegroundColor Green "---------------"
Write-Host -ForegroundColor Green " - CSV Export -"
Write-Host -ForegroundColor Green "---------------"
}
$sitesList | Where-Object {$_} | Export-Csv -Delimiter "$delimiter" -Path "SitesUsage.csv" -notype
  If($displayMessages)
{Write-Host "Export file 'SitesUsage.csv' successfully generated."}
 
  # Email notification
If($SMTPServer)
{SendEmail "SitesUsage.csv"}

# End
If($displayMessages)
{
Write-Host -ForegroundColor Green "---------------------------------"
Write-Host -ForegroundColor Green "- Script started : $DateStarted -"
Write-Host -ForegroundColor Green "- Script finished : $(Get-date) -"
Write-Host -ForegroundColor Green "---------------------------------"
}
Exit
}

No comments:

Post a Comment