Friday, August 5, 2016

Powershell Script to Get SharePoint SiteUsage information


Hi Readers,

There was a requirement to get the sites that were not used , so that we can archive them.
I found some blogs with getting last modified information using the database but the issue is it wasn's correct as all the sites had a modified date which is very recent. This may be due to search crawls.

I came up with some functions that will be useful, here the last modified date and time and the people with full control access will be listed. the purpose of this script will be informing the people with full permissions.

#Get the last Modified information of a site
function GetSiteModifiedInformation
{
    #First Argument will be the site collection url
 $siteUrl=$args[0]
    #Ouput file name or path
 $filename=$args[1]

    #Check if file url is provided
 if($siteUrl -eq $null -or $siteUrl -eq '')
 {
  Write-Host "Please provide a siteUrl" -ForegroundColor Red
  return;
 }
 
    
    Write-Host "Getting Site Information" -ForegroundColor Yellow
    #Get Site using url
    $web=Get-Spweb $siteUrl

    Write-Host "Site Name : "$web.Title
    Write-Host "Created : "$web.Created
    $maxDate=GetLastModifiedListTime $web
    
    #Iterate subsites and get info from subsites
    foreach($spsite in $web.Webs)
    {
        $val=GetLastModifiedListTime $spsite
        
        if($val -gt $maxDate)
        {
            $maxDate = $val
        }
    }

    #Get all users of the site
    $userString='';
    $users = $web.siteusers
    foreach ($user in $users) {
        #Filter users with full control
        if ($web.DoesUserHavePermissions($user,[Microsoft.SharePoint.SPBasePermissions]::FullMask)) {
            $userString= $userString+$user.Name+';'
        }
    }

    Write-Host "Last Modified "$maxDate
    Write-Host $userString
    $name=$web.Title;

    #Add site information to file name
    Add-Content $filename "$siteUrl,$name,$maxDate,$userString"
    $web.Dispose()
}

function GetLastModifiedListTime
{
    #A SPWeb Object is required here
    $site= $args[0]

    #create a date variable with minimum date value
    $date = [DateTime]::MinValue
 
 foreach($list in $web.Lists)
 {
        #Get the most recently updated sharepoint list
  if($date -lt $list.LastItemModifiedDate -and !$list.Hidden)
  {
   $date=$list.LastItemModifiedDate
  }

 }
    return $date
}

#Another helper function that can be used to input a text file
#with sites urls
function GetAllSiteInfo
{
    $siteList =$args[0]
    $output=$args[1]
    $sites= Get-Content $siteList
    foreach($site in $sites)
    {
        GetSiteModifiedInformation $site $output
    }
}


Happy Coding
Guruparan Giritharan

No comments:

Post a Comment