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!

No comments:

Post a Comment