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!

Monday, January 24, 2022

Export data to one file (csv) from different lists MS SharePoint server (PowerShell)

A question was created on the forum, where it was necessary to export the elements of 2 lists, the data of which must be displayed in one file (csv) using PowerShell.

First List (List1):

Seccond List (List2):


Powershell script:
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{ 
    Write-Host "Connect Sharepoint cmd-Let" 
    Add-PSSnapin Microsoft.SharePoint.PowerShell 
}
$SPweb = Get-SPWeb "http://sp-test/sites/RU_test"

$lst1 = $SPweb.Lists["List1"]
$lst2 = $SPweb.Lists["List2"]
$columns1 = ($lst1.Fields | where {$_.Title -like "column*"}).Title
$columns2 = ($lst2.Fields | where {$_.Title -like "column*"}).Title

$linesCount=$lst1.ItemCount
$colCount1 = $columns1.Count
$colCount2 = $columns2.Count
$result = @()
for ($line=0; $line -lt $linesCount; $line++)
{
    $line1 = $lst1.Items[$line]
    $line2 = $lst2.Items[$line]
    $props = @{}
    for ($col=0; $col -lt $colCount1; $col++)
    {
        $props+=@{$columns1[$col]=$line1[$columns1[$col]]}
    }
    for ($col=0; $col -lt $colCount2; $col++)
    {
        $props+=@{$columns2[$col]=$line2[$columns2[$col]]}
    }
    $result += New-Object PSObject -Property $props
}
$result | Export-Csv -Path 'C:\Temp\Export.csv' -NoTypeInformation -Encoding unicode -Delimiter "`t"

Run Powershell script and checking your file csv

Happy Coding!