Skip to content

How to create custom SharePoint 2013 list using PowerShell?

SharePoint provides an interface called AddFieldAsXml. This basically creates a field based on the specified schema. Nothing fancy. Right?

However, this can be very handy when you want to create your own custom lists in SharePoint programmatically. I will be using PowerShell as an example to demonstrate how you can simply create SharePoint Lists based on plain, simple xml definitions.

To start with, I created an xml template based on which I want to create my custom list using PowerShell.


<!--?xml version="1.0" encoding="utf-8"?-->

	
	
	 	
	
            0 - 10000
            
                0 - 10000
                10000 - 50000
                50000 - 100000
                100000 or more
            
       	

In this example, I have used Text, Number, Date and Choice as the Field Types. But this could be anything which is supported by SharePoint or even your own content types. Check the documentation on MSDN for Field Element.

Next step is to read this xml file, parse it and use the AddFieldAsXml method to create fields in this list. The PowerShell snippet below does the trick. Straight and Simple. Isn’t it?


Add-PSSnapin Microsoft.SharePoint.PowerShell 

function CreateList($siteCollectionUrl, $listName, $templateFile){
	
	$spWeb = Get-SPWeb -Identity $siteCollectionUrl 
	$spTemplate = $spWeb.ListTemplates["Custom List"] 
	$spListCollection = $spWeb.Lists 
	$spListCollection.Add($listName, $listName, $spTemplate) 
	$path = $spWeb.url.trim() 
	$spList = $spWeb.GetList("$path/Lists/$listName")
	$templateXml = [xml](get-content $templateFile)
	foreach ($node in $templateXml.Template.Field) {
	
		$spList.Fields.AddFieldAsXml($node.OuterXml, $true,[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)
	}
	$spList.Update()
}


$siteCollectionUrl = "http://manas.com"
$listName = "New Custom List"
$templateFile = "template.xml"

CreateList $siteCollectionUrl $listName $templateFile

And here is the result, just by configuration in xml file you can create lists using PowerShell.

SharePoint Create List

Download Example

Happy Coding!

Published inUncategorized

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *