Friday, May 17, 2013

SharePoint Powershell Create a new list with different column types

Scenario:
Murali ( my collegue ) was looking for a quick script to create a list using PS with diff columns types.

Solution:
PS - Love it - Google + little brain - recipe ready

Code:

clear
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell
 
try 
{
 
$TestSiteUrl = "http://extranet.contoso.com" #provide site url in this variable
 
$ListName = "KPIConfigList"   #listName

$ListDescription = "KPI config list" #list description
 
$myTestWeb = Get-SPWeb -identity $TestSiteUrl   #Get web object
 
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList  #GenericList template
 
write-host "Adding list" $ListName
 

$myCustomList = $myTestWeb.Lists[$ListName]
 
if($myCustomList -eq $null) 
{
 
  $lstId = $myTestWeb.Lists.Add($ListName,$ListDescription,$listTemplate)
 
  $myCustomList = $myTestWeb.Lists[$ListName]
 
    #Add columns
 
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text 

    $myCustomList.Fields.Add("TextField",$spFieldType,$false)

   #Add columns    
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Number 

    $myCustomList.Fields.Add("Order",$spFieldType,$false)

   #Add columns
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Boolean 

    $myCustomList.Fields.Add("IsDefault",$spFieldType,$false)

   #Add columns
    $choices = New-Object System.Collections.Specialized.StringCollection 

    $choices.Add("Client") 

    $choices.Add("Unit")

    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice 

    $myCustomList.Fields.Add("Type",$spFieldType,$false,$false,$choices) 
     
    #Update
    $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
Article:
Other column types
Powershell

1 comments:

Unknown August 5, 2014 at 8:57 AM  

Have you ever created an external list using powershell>? I'm trying to figure out how I would specify what external content type to leverage. I know I will have to change the list template type to the following;
[Microsoft.SharePoint.SPListTemplateType]::ExternalList