Creating Custom Lists in SharePoint with PowerShell

Shall we start this blog with some simple PowerShell commands? The following snippet creates a Custom List in SharePoint on-prem. Notice that the code checks for the existence of the list before creating it – because typically you will be using this in a larger provisioning script, and it makes sense to let your code run more than once – so as you build a solution, you can just add new elements and run it again.

# Open a connection to a SharePoint site
$web = Get-SPWeb "https://server/sites/sitecollection/subsite"

# set the internal and display names of the list
$list_internal_name = "audittrail"
$list_display_name = "Audit Trail"

if ($web.Lists[$list_display_name]) {

   # if the list exists, get it
   $list = $web.Lists[$list_display_name]

} else {

   # if the list does not exist, create it
   $web.Lists.Add($list_internal_name, "", "GenericList") > $null
   $list = $web.Lists[$list_internal_name]
   $list.Title = $list_display_name
   $list.ContentTypesEnabled = $true
   $list.EnableVersioning = $true
   $list.NavigateForFormsPages = $false
   $list.Update() > $null

}

# Release resources
$web.Close()
$web.Dispose()

Notice that I’m enabling versioning and content types on the list – because typically you would be setting up fields on the list next, and you should always really do that via site content types, and add them to the list.

Posted by Jonathan Beckett in Notes, 0 comments