Monday, March 14, 2022

SharePoint Audit (PowerShell)

And again we return to the questions of the forum, where the audit of the SharePoint server was discussed, in which it was necessary to output information to the file about the file name, user, duration and events.

Powershell script:
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction:SilentlyContinue)) 
{ 
    Add-PsSnapin Microsoft.SharePoint.PowerShell 
}
$webURL = "http://sp-test/sites/RU_test"
$docLibraryName = "Documents"
$User = 'i:0#.w|micro\administrator'
$web = Get-SPWeb $webURL
$docLibrary = $web.Lists[$docLibraryName] 
$audit = $docLibrary.Audit
$auditEntries = $audit.GetEntries()
$targetUserId =  $web.AllUsers | Where{$_.UserLogin -eq 'i:0#.w|micro\administrator'} 
$Output = @()
foreach($entry in ($auditEntries | Select -unique))
{
    $FileName = $entry.DocLocation
    $userId = $entry.UserId
    $userEntry = $web.AllUsers | Where{$_.ID -eq $userId}
    $userName = $userEntry.UserLogin
    $Output+=New-Object -TypeName PSObject -Property @{
        FileName = $FileName
        userName = $userName
        Occurred = $entry.Occurred
        Event = $entry.Event
    } | Select-Object FileName,userName,Occurred,Event
}
$Output | Export-Csv -Path 'C:\Temp\audit.csv' -NoTypeInformation -Encoding unicode -Delimiter "`t"
Run Powershell script and checking your file csv:

Happy Coding!

No comments:

Post a Comment