Saturday, August 29, 2015

PowerShell Script To Get Documents Last Updated Details


Hi,

We had requirement to get the below details of all the files in a document library of last month as report.
This report needs to be sent to customer as an attachment through email.


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"
$list=$web.Lists["doclibname"]
$fromaddress = "abc@domain.com"
$toaddress = " def@domain.com "
$ccaddress = "xyz@domain.com "
$auditloglib=$web.Lists["AuditLogReports"]
$reportid=Get-Random


$context = Get-SPServiceContext $site

  $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 Last Updated Data
try
   {
   
    

    $Headers = 'FileName,Description,Modified,Created By,Modified By,Path,Created'

    $filename = "D:\filename-" + $sd.Date.Date.ToString("MMM") + $sd.Date.Date.ToString("yy")+$reportid + ".csv"

   


    Add-Content $filename $Headers
    $Items = $list.items
    Write-Host  "Item Count" + $Items.Count

               

    foreach($MItem in $Items)   
    
    {
        Write-Host $Items.Count
        Write-Host $MItem["Name"]
        Write-Host $MItem["Description"]
        Write-Host $MItem["Modified"]
        Write-Host $MItem["Created By"]
        Write-Host $MItem["Modified By"]
        Write-Host $MItem["Path"]
        Write-Host $MItem["Created"]       
        
        $DocDetails = $MItem["Name"]+","+$MItem["Description"]+","+$MItem["Modified"]+","+$MItem["Created By"].Split("#")[1] +","+$MItem["Modified By"].Split("#")[1]+","+$MItem["Path"]+","+$MItem["Created"]       
        Add-Content $filename $DocDetails
    }
    $files = Get-ChildItem -Path $filename -Force -Recurse
foreach ($file in $files)
        {
          
          $stream = $file.OpenRead()

          $done= $auditloglib.RootFolder.Files.Add($file.Name, $stream, $true)

          $stream.Close()
         
          Write-Host $done.Name  "Uploaded into the Document Library"$auditloglib -BackgroundColor Green   
               

        }
Write-Host "Last Updated Report Uploaded successfully into"+$auditloglib
#############Email for Last Updated Data####################################
$Subject = "Sales Tools Last Updated-" + $sd.Date.Date.ToString("MMM")+$sd.Date.Date.ToString("yy")
$body = "Hi, Please find attached Last Updated report for the Month :" + $sd.Date.Date.ToString("MMM") +$sd.Date.Date.ToString("yy")
$attachment = $filename
#SMTP IP Address of Production
$smtpserver = "0.0.0.0"
$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()
$file.Delete()
#######################################################    
  }
  catch
    {
  
   Add-Content D:\Logs\LastUpdatedLogReport.txt $DocNameError
    }
#EndRegion Last Updated Data

Post generating the report through csv file.

We are uploading the same to document library and

We are deleting the same from the physical path through Power Shell script


Thursday, August 27, 2015

PowerShell Script of new Additions of a Document Library

Hi,

There was a requirement to our customer i.e.

Every month email should be triggered to the customer with count of new document uploads of the preceding month.
Along with this customer requires the below details of additions as an attachment


For this, first we have created site columns as below
Below are settings of the view that has been created
"]
$fromaddress = "abc@domain.com"
$toaddress = " abc@domain.com "
$ccaddress = " abc@domain.com "
$auditloglib=$web.Lists["AuditLogReports"]
$reportid=Get-Random

$context = Get-SPServiceContext $site

  $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 Sales Workshop Additions
$view = $stlist.Views["CurrentMonth"]
$items = $stlist.GetItems($view)
$salestoolsadditions = 0
$salestoolsadditions = $items.Count
$Headers = 'FileName,Description,Modified,Created By,Modified By,Created'
$filename = "D:\NewAdditions-" + $sd.Date.Date.ToString("MMM") + $sd.Date.Date.ToString("yy")+$reportid + ".csv"
Add-Content $filename $Headers
foreach($MItem in $items)
{
        Write-Host $MItem["Name"]
        Write-Host $MItem["Description"]
        Write-Host $MItem["Modified"]
        Write-Host $MItem["Created By"]
        Write-Host $MItem["Modified By"]       
        Write-Host $MItem["Created"]
        
        $DocDetails = $MItem["Name"]+","+$MItem["Description"]+","+$MItem["Modified"]+","+$MItem["Created By"].Split("#")[1] +","+$MItem["Modified By"].Split("#")[1]+","+$MItem["Created"]       
        Add-Content $filename $DocDetails      
}
$files = Get-ChildItem -Path $filename -Force -Recurse
foreach ($salestoolsadditionsfile in $files)
        {
          
          $stream = $salestoolsadditionsfile.OpenRead()

          $done= $auditloglib.RootFolder.Files.Add($salestoolsadditionsfile.Name, $stream, $true)

          $stream.Close()
         
          Write-Host $done.Name  "Uploaded into the Document Library"$auditloglib -BackgroundColor Green   
               

        }       
    
#EndRegion Sales Tools Additions

#############Email for New Additions ####################################
$Subject = "New Additions for the Month of -" + $sd.Date.Date.ToString("MMM")+$sd.Date.Date.ToString("yy")
$body = "--------------------------------------------------------------------------------------------"<br>New Additions in Sales Tools are - "+$salestoolsadditions<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()
#######################################################

}
catch
{
Add-Content D:\Logs\SalesToolsNewAdditionsLogReport.txt $DocNameError
}
###################################### Email for New Additions ###########################################################################

Finally the output is as below through attachment in the mail


Wednesday, August 26, 2015

PowerShell Script to get the Usage Report

Hi,

We had a requirement of Usage Report of preceding month i.e.

The usage of files in a document library needs to be sent for customer as an attachment

For this we have fetched the data from audit logs 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"
$list=$web.Lists["doclibname"]
$fromaddress = "abc@domain.com"
$toaddress = "def@domain.com"
$ccaddress = "ghi@domain.com"
$auditloglib=$web.Lists["AuditLogReports"]
$reportid=Get-Random

$context = Get-SPServiceContext $site

  $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 Nucleus Usage Report
$wssQuery = New-Object -TypeName Microsoft.SharePoint.SPAuditQuery($site)
try
   {
   
    

    $Headers = 'Section,Folder,    File,Noof Downloads,Noof ViewCounts,Document Path,Last Updated,Vertical / Service line related details1,Vertical / Service line related details2,Vertical / Service line related details3'

    $filename = "D:\UsageReports\UsageReport-" + $sd.Date.Date.ToString("MMM") + $sd.Date.Date.ToString("yy")+$reportid + ".csv"
   


    Add-Content $filename $Headers
    $Items = $list.items
    Write-Host  "Item Count" + $Items.Count

                $wssquery.SetRangeStart($sd)
        $wssquery.SetRangeEnd($ed)

    foreach($MItem in $Items)
   
    
    {
        $wssquery.RestrictToListItem($MItem)
        $auditCol = $site.Audit.GetEntries($wssQuery)
        Write-Host "Audit Count" + $auditCol.Count
         $viewcount = 0
         $DownloadCount = 0
        if($auditCol.Count -gt 0)
        {
            foreach($auditEntry in $auditCol)
                {
                    if($auditEntry.EventSource -eq 'SharePoint')
                        {
                            $DownloadCount++
                        }
                            elseif($auditEntry.EventSource -eq 'ObjectModel')
                                        {
                                            $viewcount++
                                        }
                }
$ItemDetails = $MItem.Url.Split('/')
#switch($ItemDetails.count)
#{
Write-Host "Item Count" + $ItemDetails.Count
if($ItemDetails.Count -eq 2) { $DocDetails = "Sales Tools" + "," + "NA" + "," + $ItemDetails[1] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + "NA" + "," + "NA" + "," + "NA" + "," + $MItem.Url}
ElseIf($ItemDetails.Count -eq 3) { $DocDetails = "Sales Tools" + "," + $ItemDetails[1] + "," + $ItemDetails[2] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + "NA" + "," + "NA" + "," + "NA" + "," + $MItem.Url}                                                             
ElseIf($ItemDetails.Count -eq 4) { $DocDetails = "Sales Tools" + "," + $ItemDetails[1] + "," + $ItemDetails[3] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + $ItemDetails[2] + "," + "NA" + "," + "NA" + "," + $MItem.Url}
ElseIf($ItemDetails.Count -eq 5) { $DocDetails = "Sales Tools" + "," + $ItemDetails[1] + "," + $ItemDetails[4] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + $ItemDetails[2] + "," + $ItemDetails[3] + "," + "NA" + "," + $MItem.Url}
ElseIf($ItemDetails.Count -eq 6) { $DocDetails = "Sales Tools" + "," + $ItemDetails[1] + "," + $ItemDetails[5] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + $ItemDetails[2] + "," + $ItemDetails[3] + "," + $ItemDetails[4] + "," + $MItem.Url}
else
  { $DocDetails = "Sales Tools" + "," + $ItemDetails[1] + "," + $ItemDetails[5] +  "," + $DownloadCount + "," + $viewcount + "," + $MItem.Url + "," +  $MItem["Modified"] + "," + $ItemDetails[2] + "," + $ItemDetails[3] + "," + $ItemDetails[4] + "," + $MItem.Url}         
#default {}
#}

Write-Host $DocDetails
#$DocDetails = "Sales Tools" + ","  + $viewcount + "," + $DownloadCount + "," + $MItem.Url + "," +  $MItem["Modified"]
Add-Content $filename $DocDetails

}


               
    }

$files = Get-ChildItem -Path $filename -Force -Recurse
foreach ($file in $files)
        {
          
          $stream = $file.OpenRead()

          $done= $auditloglib.RootFolder.Files.Add($file.Name, $stream, $true)

          $stream.Close()
         
          Write-Host $done.Name  "Uploaded into the Document Library"$auditloglib -BackgroundColor Green   
               

        }


#############Email for Usage Report####################################
$Subject = "Usage Report-" + $sd.Date.Date.ToString("MMM")+$sd.Date.Date.ToString("yy")
$body = "Hi, Please find attached Usage report for the Month :" + $sd.Date.Date.ToString("MMM") +$sd.Date.Date.ToString("yy")
$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()
$file.Delete();
#######################################################


}
catch
    {
   Write-Host "Error for File : " $i."Name"
   Add-Content D:\Logs\UsageReport\UsageLogReport.txt $DocNameError
    }
#EndRegion Usage Report       
  
Finally we got the required email triggered as an attachment as below

Attachment