Friday, September 7, 2012

Create List and Add Column to the List

Create List
Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
try
{
$TestSiteUrl = "http://mysitecollection/mysite" #provide site url in this variable
$ListName = "EmpInfo"   #listName
$ListDescription = "Employee information list" #list description
$myTestWeb = Get-SPWeb -identity $TestSiteUrl   #Get web object
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList  #GenericList template
write-host "Adding list" $ListName
#column1 schema xml
$firstNameColXml = "<Field Type='Text' DisplayName='FirstName' Required='TRUE' EnforceUniqueValues='FALSE'
MaxLength='255' StaticName='FirstName' Name='FirstName' />"
#column2 schema xml
$lastNameColXml = "<Field Type='Text' DisplayName='LastName' Required='FALSE' EnforceUniqueValues='FALSE'
MaxLength='255' StaticName='LastName' Name='LastName' />"
#build the list url
$listUrl = $myTestWeb.ServerRelativeUrl + "/lists/" + $ListName;
#we can't use getlist here as the method raises filenotfoundexception if the list url is not there
$myCustomList = $myTestWeb.Lists[$ListName]
if($myCustomList -eq $null)
{
  $lstId = $myTestWeb.Lists.Add($ListName,$ListDescription,$listTemplate)
  $myCustomList = $myTestWeb.GetList($listUrl) # use getlist here as  the list already exists
#Add columns
$myCustomList.Fields.AddFieldAsXml($firstNameColXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)
$myCustomList.Fields.AddFieldAsXml($lastNameColXml,$true,
[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)
 $myCustomList.Update()
 write-host "list created successfully" $ListName
}
else
{
  write-host "List already exists" $ListName
}
}
catch
{
  write-host "Error" $_.exception
  $errorlabel = $true
}
finally
{
  if($myTestWeb -ne $null)
 {$myTestWeb.Dispose()}
  if($errorlabel -eq $true){exit 1}
  else {exit 0}
}exit 0

Add Column to a list
$site = SPSite($workspaceUrl)
$web = $site.RootWeb
$spList = $web.Lists["YourList"]
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("YourColumn",$spFieldType,$false)
$spList.Update()

No comments:

Post a Comment