Wednesday, November 11, 2020

Export MS SQL server data to SharePoint List (PowerShell)

Due to the closure of "the blog TechNet" I transfer all my articles in the blog :)
If you need to download information from the MS SQL server table to the list on the SharePoint server, use PowerShell.
In this code, you connect to the database using SSPI and operate with standard T-SQL commands, then connect to the SharePoint list and upload the data.
Pre-requisites
1. PowerShell 2.0 and higher,
2. WSS or SharePoint server on-premises 2007, 2010, 2013, 2016, 2019.
3. SQL management studio (only view).
[System.Reflection.Assembly]::LoadWithPartialName("System.Data")
#SQL Database server
$conn = New-Object "System.Data.SqlClient.SqlConnection" -ArgumentList "server=SQLSERVER; database=USER; integrated security=SSPI"
$conn.Open()
$cmd = $conn.CreateCommand()
$cmd.CommandText = "select [LastName], [FirstName], [MiddleName], [Email], [Department], [Office], [Job] from [dbo].[OLE_USER_Destination]"
$adapter = New-Object "System.Data.SqlClient.SqlDataAdapter" -ArgumentList $cmd
#variable SQL datatable 
$table = New-Object "System.Data.DataTable" -ArgumentList "Table1"
$adapter.Fill($table)
#SharePoint List
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction:SilentlyContinue)) 
{ 
    Add-PsSnapin Microsoft.SharePoint.PowerShell 
}
    $web = Get-SPWeb http://sharepoint/sites/Department
    $list = $web.Lists["YOURLIST"]
    #Load variable SQL datatable
    $table | % { 
    $item = $list.AddItem();
    $item["LastName"]=$_.LastName;
    $item["FirstName"]=$_.FirstName;
    $item["MiddleName"]=$_.MiddleName;
    $item["Email"]=$_.Email;
    $item["Department"]=$_.Department;
    $item["Office"]=$_.Office;
    $item["Job"]=$_.Job;
    $item.Update();
}

Happy Coding!

No comments:

Post a Comment