Tuesday, 20 March 2012

Notify Users Who Leave Documents Checked Out

We have a problem with some users, who check out documents but never check them back in. I wrote a Powershell script to loop through the libraries and look for files that had been checked out for longer than 1 day. 

All of our libraries have a view called "Checked Out" documents which shows all the checked out documents in the library. The script creates a link to this view but you can easily change that to create a link to the library or directly to the file.

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
    Write-Host "Loading SharePoint Powershell Snap-in"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
}

$site = Get-SPSite http://siteurl
$SmtpServer = "smtp.yourserver.com"
$Subject = "File Checked Out Longer Than 1 Day"
$from = "service.desk@yourcompany.com"
$date = Get-Date
$Warning = ((get-date).adddays(-1))

#Loop through the webs
foreach ($web in $site.AllWebs)
{
  # loop through all lists in web
  foreach ($list in $web.Lists)
  {
    # examine if BaseType of list is NOT a Document Library
    if ($list.BaseType -ne "DocumentLibrary")
    {
      # forget the rest and return to top
      continue
    }
    # loop through each item
    foreach ($item in $list.Items)
    {
      $file = $item.File   
      if(($file.CheckOutStatus -ne "None") -and ($file.CheckedOutDate -lt $warning))
      {
        $User = $file.CheckedOutByUser
        $Email = $file.CheckedOutByUser.email
        $body = "Hi " +$User + ",

You have had the following file checked out from Sharepoint for more than a day. Click on the link below to see checked out documents in this library.

" +$file.name + "     """ + $web.url + "/" + $list + "/Forms/Checked%20Out%20Documents.aspx" + """

Please check this document back in If you are no longer using it.

Thanks"
        $smtp = new-object Net.Mail.SmtpClient($SmtpServer)
        $smtp.Send($from, $Email, $subject, $body)          
      }
    }
  }
}