Quantcast
Channel: SharePoint Diary
Viewing all articles
Browse latest Browse all 1058

Import From CSV File into SharePoint List using Powershell

$
0
0
Periodically, We needed the data from a CSV file, which is generated by an external Third-party application, to be imported to SharePoint 2010 List. To fulfill this requirement,  I wrote a quick PowerShell script which will read the CSV file and import the data into SharePoint list using PowerShell.

Powershell Script to import from CSV file to SharePoint 2010 list

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Read the CSV file - Map the Columns to Named Header (CSV File doesn't has Column Header)
$CSVData = Import-CSV -path "C:\Data.csv" -Header("Title", "Description", "Priority", "AssignedTo", "DueDate", "Status")

#Get the Web
$web = Get-SPWeb -identity "http://sharepoint.crescent.com/sites/Marketing/"

#Get the Target List
$list = $web.Lists["Log"]

#Iterate through each Row in the CSV
foreach ($row in $CSVData) 
 {
   $item = $list.Items.Add();
   
   $item["Title"] = $row.Title
   $item["Description"] = $row.Description
   $item["Priority"] = $row.Priority

   #Set the People Picker Field value
   $item["Assigned To"] = Get-SPUser -Identity $row.AssignedTo -web "http://sharepoint.crescent.com/sites/Marketing/"
    
   #Set the Date Field value
   $item["Due Date"] = Get-Date $row.DueDate

   $item["Status"] = $row.Status
   $item.Update()
 }

We scheduled this script through Windows Task Scheduler: How to schedule a powershell script using windows task scheduler

In an another case, before importing a list item from CSV file, I had to check whether the item which is being added, is already exists in the List. If It doesn't exists, let the script add new item from CSV file.
$ListItems = $reconciliationList.Items | Where-Object { $_.Item("Title") -eq $row.Title}

  if ($ListItems -eq $null)
    { 
      #ADD Item to the List
    }

Update Lookup values in PowerShell:
Unlike other fields, SharePoint look-up fields can'tbe set directly. We have to get the lookup parent id, to update the lookup field values.
 #For Lookup values: Lookup Parent List
 $DepartmentList=$web.Lists["Department"]

    #Get the Lookup Item from Parent List
    $LookupItem = $departmentList.Items | Where-Object { $_.Item("Title") -eq $row.Department}

	if($LookupItem -ne $null)
	{
       	  $deptLookup = New-Object Microsoft.Sharepoint.SPFieldLookupValue($LookupItem.ID,$row.Department)
	}

      #Set the Lookup field value
      $item["Department"] = $deptLookup
   
    $item.Update() 

Viewing all articles
Browse latest Browse all 1058

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>