December 4, 2016

// // Leave a Comment

Create multiple columns inside SharePoint List using Powershell

Hi All,

1) In this post we will be seeing how to add multiple columns inside SharePoint List/Library and adding to the view

2) Refer the below posts in the powershell series.




Bulk Lists and Libraries in SharePoint

Bulk File upload to sharepoint library

3) Create a CSV File like below



4) Use the below Powershell script


#This script creates site columns from the given csv file
#Author: Prem Kumar
#Date: Feb 11 2015


 param(
[string]$rooturl = $(Read-Host -prompt "Enter Web Application Root URL...?"),
[string]$listname = $(Read-Host -prompt "Enter the list name...?"),
[string]$csvpath = $(Read-Host -prompt "Enter the CSV Path...?")
)

try
{

$osite = Get-SPWeb $rooturl 
$olist= $osite.Lists[$listname]
$columnstoadd= Import-Csv $csvpath
$oView = $oList.DefaultView 
$oView.ViewFields.View.ViewFields.DeleteAll()
$oView.ViewFields.Add("LinkTitle")

write-host "Adding Columns to the list $listname"
write-host "Loading Columns data from CSV $csvpath"


foreach($column in $columnstoadd)
{
 if($olist.Fields[$column.ColumnName] -eq $null)
 {
    $type=$column.DataType
    if($type -eq "Choice")
    {
        
        $choiceFieldChoices = @($column.Choices.Split(","))
        # Declare a new empty String collection
        $stringColl = new-Object System.Collections.Specialized.StringCollection
        # Add the choice fields from array to the string collection
        $stringColl.AddRange($choiceFieldChoices)
        # Create a new choice field and add it to the web using overload method
        $spFieldType = [Microsoft.SharePoint.SPFieldType]::$type 
        $olist.Fields.Add($column.ColumnName,$spFieldType,$false,$false, $stringColl)
        # Update the list
        $olist.DefaultView.ViewFields.add($column.ColumnName)
        $olist.Update()
        write-host "Field added $column"
    }
    else
    {
        $olist.Fields.Add($column.ColumnName,[Microsoft.SharePoint.SPFieldType]::$type,$false)
        $olist.DefaultView.ViewFields.add($column.ColumnName)
        $olist.Update()
        write-host "Field added $column"
    }
 }
 else
 {
    write-host "Column $column already exists in list $listname"
 }


$oView.ViewFields.Add($column.ColumnName) 
$oView.Update()

}
}

catch 
{
    write-host "Exception in Adding List Columns $_.Exception.Message"
}
finally
{
    write-host "Exit of Add List Columns..."
    $osite.Dispose()
}

0 comments:

Post a Comment