SharePoint – PowerShell – Export List Data from a view to CSV and Save in a SharePoint Library

I really like this script.  You create a view in the SharePoint UI with the fields you want, filters, etc., (Script does not include sorting) and it will export that data to a CSV file and save it on your SharePoint site in a Library.  You could also create a PowerShell scheduled task on your server to run a nightly local backup. Let me know if this helps anyone.


$url="http://teamsite"
$lists =
"Customers",
"Customer Calls"
$viewname = "Backup View"
#Make the view name the same for all lists
$libraryname="Backups"
#Location of the backups - create this SharePoint Library in advance
$web = get-spweb $url
foreach($listname in $lists)
{
$list = $web.lists[$listname]
$date = get-date -format yyyy-MM-dd
$webfolder = $web.getfolder($libraryname)
$view = $list.views[$viewname]
$view.rowlimit = 100000
#This will temporarily update the view row limit - it gets set back to 30 at the end of the script
$view.update()
$vfields=$view.viewfields
$lfields=$list.fields
$efields=@()
foreach($vf in $vfields)
{
foreach($lf in $lfields)
{
if($lf.internalname -eq $vf)
{
$efields += $lf.title
}
}
}
$items = $list.getitems($view)
if($items.count -gt 0)
{
$exportlist = $null
$exportlist = @()
$items | foreach {
$hash = $null
$hash = @{}
foreach($ef in $efields)
{
$hash.add($ef, $_[$ef])
}
$obj = New-Object PSObject -Property $hash
$exportlist += $obj
}
$sel=@()
foreach($efield in $efields)
{
$sel+=$efield
}
$expath = "E:\ListDataBackups\"+[string]$date+'-'+$listname+'.csv'
$exportlist |select $sel | Export-Csv -path $expath -notypeinformation
$file = get-item -path $expath
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
$spFile = $webfolder.Files.Add($webfolder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
$fileStream.Close();
$view.rowlimit = 30
$view.update()
}
}
$web.dispose()

This entry was posted in PowerShell, SharePoint 2010 and tagged , , , , . Bookmark the permalink.

2 Responses to SharePoint – PowerShell – Export List Data from a view to CSV and Save in a SharePoint Library

  1. Naresh says:

    Thank you for sharing nice article. it is saved my time.

Leave a comment