Search This Blog

Tuesday, March 24, 2015

Add Fields To SharePoint List with PowerShell in SharePoint 2010 (Part1)

Adding field of type ‘Single line of text’

$TestSiteUrl = "http://XXXXXXXXX:XXXX/sites/XXXXX"
$NewWebobj = Get-SPWeb -identity $TestSiteUrl
$newListName = "EmpList"
$newListDescription = "Employee Information"
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList
$lstId = $NewWebobj.Lists.Add($newListName,$newListDescription,$listTemplate)
write-host "list " $ListName " created successfully" $ListName -ForegroundColor Green

$listUrl = $NewWebobj.ServerRelativeUrl + "/lists/" + $newListName;
$myCustomList = $NewWebobj.GetList($listUrl)

#column of type 'Single line of text'
$firstNameColXml = "<Field Type='Text' DisplayName='FirstName' Required='TRUE' MaxLength='255'
StaticName='FirstName' Name='First Name' />"

$myCustomList.Fields.AddFieldAsXml($firstNameColXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

$myCustomList.Update()

Above code will create SharePoint custom list ‘EmpList’ with column ‘FirstName’ which is of type ‘Single line of text’. 

Adding field of type ‘Multiple lines of text’

$multiLineCol1 = "<Field Type='Note' DisplayName='MultiLineCol1' Required='FALSE' NumLines='6' RichText='FALSE'
Sortable='FALSE' StaticName='MultiLineCol1' Name='MultiLineCol1' />"

$myCustomList.Fields.AddFieldAsXml($multiLineCol1,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

Adding field of type ‘Choice’

$choiceCol1 = "<Field Type='Choice' DisplayName='ChoiceCol1' Required='FALSE' Format='Dropdown'
FillInChoice='FALSE' StaticName='ChoiceCol1' Name='ChoiceCol1'>
            <Default>MyChoice1</Default>
            <CHOICES>
                <CHOICE>MyChoice1</CHOICE>
                <CHOICE>MyChoice2</CHOICE>
            </CHOICES>
           </Field>"

$myCustomList.Fields.AddFieldAsXml($choiceCol1,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

Adding field of type ‘Number’

$numCol1 = "<Field Type='Number' DisplayName='NumCol1' Required='FALSE' Name='NumCol1'/>"
$myCustomList.Fields.AddFieldAsXml($numCol1,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)


Adding field of type ‘Date and Time’

$fldXml = "<Field Type='DateTime' DisplayName='DataTimeCol1' Format='DateOnly'   Name='DataTimeCol1'/>"
$myCustomList.Fields.AddFieldAsXml($fldXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

No comments:

Post a Comment