Wednesday, June 1, 2011

Get SharePoint audit details across the farm for specific users

This code snippet gets all audit details for specific users across an entire SharePoint 2007/2010 farm and saves them to a CSV file. I have also added a method to include a file extension column. This comes in handy as you will likely want to filter out web extensions like aspx, html, css, etc., picture formats, and folders. In order to get any data, auditing will have to have been enabled at the Site Collection level through site settings or programmatically at the item level. Keep in mind that this will take some time if your AuditData tables are very large, so in this case you will want to make further refinements by filtering by site collection, list, or list item. Site collections can be filtered out by tweaking the loop statements below, while you can filter out list or list items by updating the RestrictToList or RestrictToListItem methods of the SPAuditQuery object.
Helpful Links
Configure audit settings for a site collections
http://office.microsoft.com/en-us/sharepoint-server-help/configure-audit-settings-for-a-site-collection-HA010099726.aspx
Custom Auditing in SharePoint
http://msdn.microsoft.com/en-us/magazine/cc794261.aspx

Instructions
Create a c# Console Application in Visual Studio, add a reference to Microsoft.SharePoint, and then add the following code to Program.cs. This will work with SharePoint 2007 and 2010 as long as you reference the correct assembly. Don’t forget to make sure your Visual Studio project’s Platform Target is Any CPU or x64.


using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPCheckAudit
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            GetUserAuditEntries(new string[] { "corp\\jdoe", "corp\bsmith" });

        }

        public static void GetUserAuditEntries(string[] userLogins)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("User,FullUrl,DocLocation,Event,EventData,EventName,EventSource,ItemId,ItemType," +
                "LocationType,MachineIP,MachineName,Occurred,SiteId,SourceName,UserId\r\n");
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPServiceCollection services = SPFarm.Local.Services;
                    foreach (SPService curService in services)
                    {
                        if (curService is SPWebService)
                        {

                            SPWebService webService = (SPWebService)curService;
                            foreach (SPWebApplication spWebApplication in webService.WebApplications)
                            {
                                foreach (SPSite site in spWebApplication.Sites)
                                {
                                    Console.WriteLine("Checking Site: " + site.ID + " " + site.PortalName);

                                    foreach (string userLogin in userLogins)
                                    {
                                        try
                                        {
                                            SPUser user = site.RootWeb.AllUsers[userLogin];
                                            SPAuditQuery auditQuery = new SPAuditQuery(site);
                                            SPAuditEntryCollection auditItems = site.Audit.GetEntries(auditQuery);
                                            foreach (SPAuditEntry auditItem in auditItems)
                                            {
                                                sb.Append(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"" +
                                                    ",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\",\"{14}\"\r\n",
                                                    userLogin, GetExtension(auditItem.DocLocation), auditItem.DocLocation, auditItem.Event, 
                                                    auditItem.EventData, auditItem.EventName, auditItem.EventSource, auditItem.ItemId, 
                                                    auditItem.ItemType, auditItem.LocationType, auditItem.MachineIP, auditItem.MachineName, 
                                                    auditItem.Occurred, auditItem.SiteId, auditItem.SourceName, auditItem.UserId));
                                            }
                                        }
                                        catch (SPException spex)
                                        {
                                            if (!spex.Message.Contains("User cannot be found."))
                                            {
                                                throw (spex);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine(ex.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV File|*.csv";
            sfd.Title = "Save File";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (var writer = new StreamWriter(sfd.FileName, true))
                {
                    writer.WriteLine(sb.ToString());
                }
            }
        }

        public static string GetExtension(string docLocation)
        {
            string extension = string.Empty;
            if (docLocation.Substring(docLocation.Length - 4, 1) == ".")
            {
                extension = docLocation.Substring(docLocation.Length - 3, 3);
            }
            else if (docLocation.Substring(docLocation.Length - 5, 1) == ".")
            {
                extension = docLocation.Substring(docLocation.Length - 4, 4);
            }
            else
            {
                extension = "folder";
            }
            return extension;
        }
    }
}

2 comments:

  1. Thank you for sharing such relevant topic with us. I really love all the great stuff you provide. Thanks again and keep it coming.

    ReplyDelete
  2. The essential web-analytics solution for SharePoint-based sites and portals. More 70 reports, wide customization, great features, free trial.
    Homepage: http://www.harepoint.com/Products/HarePointAnalyticsForSharePoint/Default.aspx

    ReplyDelete