Ensure_List

Language:
PowerShell
Keywords:
SharePoint
Code Snippet

## Ensures that an SPList exists.. if it does, do nothing; if it does not, create it based on parameters
Function Ensure_List( [Microsoft.SharePoint.SPWeb]$tWeb
                    , $tListName
                    , $tListDescription = ""
                    , [Microsoft.SharePoint.SPListTemplateType]$SPListTemplateType = [Microsoft.SharePoint.SPListTemplateType]::GenericList
                    , $tListUrl = ""
                    , [System.Boolean]$OnQuickLaunch = $true
                    , $DocTemplateName = "None"
                    ) {
    if (!$tWeb.Lists.TryGetList($tListName)) {
        Write-Output([System.String]::Format("List [{0}] : Creating in Web [{1}]", $tListName, $tWeb.Url))
        if ([System.String]::IsNullOrEmpty($tListUrl)) {
            $tList = $tWeb.Lists.Add($tListName, $tListDescription, $SPListTemplateType)

            if ($tList.OnQuickLaunch -ne $OnQuickLaunch) {
                $tList.OnQuickLaunch = $OnQuickLaunch
                $tList.Update()
            }

        
} else {
            # use the internal static method Microsoft.SharePoint.LegacyListTemplate::LookupAssociatedFeatureId
            # while not ideal, it saves a bunch of space, and lots of hard coded values.
            $rLegacyListTemplate = $SPListTemplateType.GetType().Assembly.GetType("Microsoft.SharePoint.LegacyListTemplate", $true, $false)
            $rLookupAssociatedFeatureId = $rLegacyListTemplate.GetMethod("LookupAssociatedFeatureId")
            $rLookupAssociatedFeatureId_Params = New-Object System.Collections.ArrayList
            $rLookupAssociatedFeatureId_Params.Add($SPListTemplateType) | Out-Null
            $tLookupAssociatedFeatureId = $rLookupAssociatedFeatureId.Invoke($rLegacyListTemplate, $rLookupAssociatedFeatureId_Params.ToArray())
            
            if ($OnQuickLaunch) {
                $QuickLaunch = [Microsoft.SharePoint.SPListTemplate+QuickLaunchOptions]::On
            } else {
                $QuickLaunch = [Microsoft.SharePoint.SPListTemplate+QuickLaunchOptions]::Off
            }
            $tDocTemplateId = $tWeb.DocTemplates | where { $_.Name -eq $DocTemplateName }
            $tWeb.Lists.Add($tListName, $tListDescription, $tListUrl, $tLookupAssociatedFeatureId, $SPListTemplateType, $tDocTemplateId, $QuickLaunch) | Out-Null
            $QuickLaunch = $nul
        }
        $tWeb.Update()
        
    } # if $tWeb.Lists.TryGetList() fails
} # Function Ensure_List(...)


Created 2011-10-13
comments powered by Disqus
Login