This post goes hand in hand with my recent post on retrieving available List and Library templates – although in this PowerShell Function I’m calling the Add method of an SPWeb Object to create lists and libraries.
Most of the ‘code’ in this function comes from the 5 parameters I’m using, but the actual function boils down to the following lines:
Start-SPAssignment -Global $SPWeb = Get-SPWeb -Identity $Web $listTemplate = $SPWeb.ListTemplates[$Template] $SPWeb.Lists.Add($ListUrl,$Description,$listTemplate) $list = $SPWeb.Lists[$ListUrl] $list.Title = $ListTitle $list.Update() $SPWeb.Dispose() Stop-SPAssignment -Global
Essentially I’m just grabbing an SPWeb object from the $Web parameter, I’m then grabbing a ListTemplate from the $ListTemplate parameter, I then call the Add() method to provision the list or library. Once that’s done, I change the Title to the value given in the $ListTitle parameter, hopefully leaving the URL a nice friendly name with no spaces. I then use the Update() and Dispose() methods to update and clean-up, and finally I close out the SPAssignment.
Here’s the complete function:
function New-SPList { <# .Synopsis Use New-SPList to create a new SharePoint List or Library. .Description This advanced PowerShell function uses the Add method of a SPWeb object to create new lists and libraries in a SharePoint Web specified in the -Web parameter. .Example C:\PS>New-SPList -Web http://intranet -ListTitle "My Documents" -ListUrl "MyDocuments" -Description "This is my library" -Template "Document Library" This example creates a standard Document Library in the http://intranet site. .Example C:\PS>New-SPList -Web http://intranet -ListTitle "My Announcements" -ListUrl "MyAnnouncements" -Description "These are company-wide announcements." -Template "Announcements" This example creates an Announcements list in the http://intranet site. .Notes You must use the 'friendly' name for the type of list or library. To retrieve the available Library Templates, use Get-SPListTemplates. .Link http://www.iccblogs.com/blogs/rdennis http://twitter.com/SharePointRyan .Inputs None .Outputs None #> [CmdletBinding()] Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string]$Web, [Parameter(Mandatory=$true)] [string]$ListTitle, [Parameter(Mandatory=$true)] [string]$ListUrl, [Parameter(Mandatory=$false)] [string]$Description, [Parameter(Mandatory=$true)] [string]$Template ) Start-SPAssignment -Global $SPWeb = Get-SPWeb -Identity $Web $listTemplate = $SPWeb.ListTemplates[$Template] $SPWeb.Lists.Add($ListUrl,$Description,$listTemplate) $list = $SPWeb.Lists[$ListUrl] $list.Title = $ListTitle $list.Update() $SPWeb.Dispose() Stop-SPAssignment -Global }
3 thoughts on “Use PowerShell to Create SharePoint Lists and Libraries”