Monday, October 22, 2012

Creating SharePoint Custom List Columns in PowerShell


I needed to create a sizable test in SharePoint using a custom list.  I did not want to manually configure each column so I build a tab delimited text file that held the column configuration options and a PowerShell script to read it.  The first column of the file provides the field name, the second provides the options (they were separated by a pipe delimiter), and the third column is the field description.  I wanted all of the questions to be Radio Button choice fields so those options were hard coded.  I also wanted a letter and appended to each answer so I created an array of letters up to G. 

$w = get-spweb http://spsite
$l = $w.lists["MyTest"]

$letters = "A|B|C|D|E|F|G"
$lttr = $letters.split("|")
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice

$file = Get-Content c:\Questions.txt

foreach ($line in $file) {
    $fields = $line.ToString().Split("`t")
    $fName = $l.Fields.Add($fields[0],$spFieldType,$True)   
    write-host $fName
    $f = $l.Fields[$fName]
    $choices = $fields[1].split("|")

    for ($i=0; $i -lt $choices.count; $i++)
        $choiceValue = $lttr[$i] + ". " + $choices[$i]
    $f.description = $fields[2]
    $f.EditFormat = "RadioButtons"


The script works like a champ, and I saved myself a little time and frustration of repetitively clicking the same options over and over again.

No comments:

Post a Comment