In my last article on document and list item auditing we looked at how you can set auditing setting with SharePoint UI.
If you’re in charge of administration of a large portal and would like to automate setting up and managing of auditing – PowerShell is your best bet.
Let’s take a look at how you can set site collection audit settings and individual list audit settings with PowerShell script. For this example, I will assume you have a team site set up at http://intranet.contoso.com
1. Create new file on a file system of the server, we’ll call it SetupAudit.ps1
2. Add the following to the contents of the file:
function SetListAuditing([Microsoft.SharePoint.SPWeb]$web)
{
$lists = $web.Lists;
for($i=0; $i -lt $lists.count; $i++)
{
if ($lists[$i] -eq [Microsoft.SharePoint.SPListTemplateType].Announcements)
{
$lists[$i].Audit.Auditflags = [Microsoft.SharePoint.SPAuditMaskType]::All;
$lists[$i].Audit.Update();
$lists[$i].Update();
}
}
}
$site = spsite "http://intranet.contoso.com" $site.Audit.Auditflags = [Microsoft.SharePoint.SPAuditMaskType]::View -bxor [Microsoft.SharePoint.SPAuditMaskType]::Update; $site.Audit.Update(); $site.allwebs | foreach-object {SetListAuditing $_ }
Above, we set the current site to the team site URL, and iterate through sub sites on the site collection. For each sub-site, we go through the list of lists and libraries and set audit on all events for the lists of type Announcement. Here is the list of more events on which you can audit.
Additionally we set site collection auditing settings to capture View and Update events happening on the site collection level.
3. Now, open SharePoint 2010 Management Shell from the start menu and run SetupAudit.ps1.
When you go back to your site collection or library auditing settings as we did in the previous article, you will see the end result setting exactly how it was applied through SharePoint UI.
To retrieve audit records from site collection using PowerShell, although those are not going to be as pretty as Excel reports we looked at in my last post, use the following PowerShell script:
function GetEvent([Microsoft.SharePoint.SPAuditEntry]$event)
{
"Audit Event: "
$event.Event;
$event.DocLocation;
"_____________"
}
$site = spsite "http://intranet.contoso.com"
$site.Audit.GetEntries([Microsoft.SharePoint.SPAuditQuery]($site)) | foreach-object {GetEvent $_ }
Enjoy!
