Tuesday 30 May 2017

How to Create Custom SharePoint 2013 List using PowerShell?

Ref : https://www.codeproject.com/articles/808246/how-to-create-custom-sharepoint-list-using-powersh

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"?>
<Template>
 <Field Type="Text" DisplayName="Name" Required="False" 

 MaxLength="255" StaticName="Name" Name="Name" />
 <Field Type="Number" DisplayName="Phone Number" 

 Required="False" MaxLength="255" 

 StaticName="PhoneNumber" Name="PhoneNumber" />
 <Field Type="DateTime" DisplayName="Date of Birth" 

 Required="False" MaxLength="255" 

 StaticName="DateOfBirth" Name="DateOfBirth" />  
 <Field Type="Choice" DisplayName="Annual Salary" 

 Required="False" Format="Dropdown" FillInChoice="FALSE" 

 StaticName="AnnualSalary" Name="AnnualSalary">
            <Default>0 - 10000</Default>
            <CHOICES>
                <CHOICE>0 - 10000</CHOICE>
                <CHOICE>10000 - 50000</CHOICE>
                <CHOICE>50000 - 100000</CHOICE>
                <CHOICE>100000 or more</CHOICE>
            </CHOICES>
       </Field> 
</Template>
In this example, I have used TextNumberDate 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.
The 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.