Automatic SharePoint list provisioning

Lists and libraries are used everywhere in SharePoint, and as your site is being used by your business users, they are likely to want you to add new lists and modify existing ones.
Unfortunately, those changes would have to be done to many existing instances of your sites – and that’s probaly a lot.
Fortunately, you have PowerShell and this sort of change can be easily scripted. Let’s see how.
For this example, I assume you’re running 2010 IW demo VM or similar type of demo environment; I am using demo Team Site with the following URL: http://intranet.contoso.com

On this environment, let’s create a new PowerShell script with the following code:

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

$SPSite = Get-SPSite | Where-Object {$_.Url -eq "http://intranet.contoso.com"}
  if($SPSite -ne $null)
  {
    $RootWeb = $SPSite.RootWeb
    $NewListTemplate = $RootWeb.ListTemplates["Custom List"]
    $NewListInstance = $RootWeb.Lists.Add("My List",
"My List Description", $NewListTemplate)

    # Add fields to the list
    $FIeldCollection = $SPList.Fields
    $Field1 = $FIeldCollection.Add("Field1",
[Microsoft.SharePoint.SPFieldType]::Text, $false)
    $Field1Instance = $FIeldCollection.GetField($Field1)
    $SPList.Update()

    $SPView = $SPList.DefaultView
    $SPViewFields = $SPView.ViewFields
    $SPViewFields.Add($Field1Instance)
    $SPView.Update()

    $SPListItem = $SPList.Items.Add()
    $SPListItem["Title"] = "New Item Title"
    $SPListItem["TextField"] = "Text Fields Value"
    $SPListItem.Update()
  }

Save, and run the script on your demo environment.
This will create a custom list on your site and add an extra field to it.
Once created, a test item will be added to the list.
You noticed we create a text type field. You can actually create all sorts of field types by referecning appropriate SPFieldType Enumeration
For more SharePoint 2010 handy solutions and tips like this one – check out my new book.
Enjoy!

This entry was posted in cloud, sharepoint 2010 and tagged , , , . Bookmark the permalink.

Comments are closed.