Monday, April 11, 2011

Powershell Script to insert large amount of ListItems in Sharepoint List

A small script I wrote to insert a large amount of items in a custom list. It is just for testing purposes, so I can learn a little bit more about optimizing SPQueries and about ListView thresholds.

if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.Sharepoint.PowerShell
}
clear
#Get-Command  -Module Microsoft.Sharepoint.PowerShell
$assignment = Start-SPAssignment
$webUrl="http://myweburl/"
$listName = "OneMillionRecords"
$spWeb = Get-SPWeb -Identity $webUrl -AssignmentCollection $assignment
$template = $spWeb.ListTemplates["Custom List"] 
$listId=$spWeb.Lists.Add($listName,"List with one million records",$template)
$spNewList = $spWeb.Lists[$listName]
$spFieldTypeText = [Microsoft.SharePoint.SPFieldType]::Note
$spFieldTypeNumber = [Microsoft.SharePoint.SPFieldType]::Number
$spNewList.Fields.Add(“Description”,$spFieldTypeText,$false)
$spNewList.Fields.Add(“ItemNr”,$spFieldTypeNumber,$false)
$i =1
$max = 1000000
while ($i -le $max) {
$j=$i.ToString()
$title="Item $j"
$itemNr=$i
$description="The Item is called Item $j and is stored with some useless text"
$newItem=$spNewList.items.Add() 
$newItem["Title"] = $title
$newItem["ItemNr"] = $itemNr
$newItem["Description"]=$description
$newitem.Update()
Write-Host $title
$i=$i+1
}
#Dispose all objects
Stop-SPAssignment $assignment

No comments:

Post a Comment