Ensure_ContentType

Language:
PowerShell
Keywords:
SharePoint
Code Snippet

## Ensures that a list exists.. if it does, do nothing; if it does not, create it based on parameters
Function Ensure_ContentType([Microsoft.SharePoint.SPWeb]$tWeb
                         , $ctId = ""
                         , [Microsoft.SharePoint.SPContentType]$ctParent = $null
                         , $ctGroupName = ""
                         , $ctName = ""
                         , $ctDescription = ""
                         ) {
    # Input Validation
    if ([System.String]::IsNullOrEmpty($ctName)) {
        throw (New-Object System.ArgumentNullException("Must provide Content Type NAME"))
    }
    if ([System.String]::IsNullOrEmpty($ctId) -xor $ctParent) {
        throw (New-Object System.ArgumentNullException("Must provide EITHER ContentTypeId ($ctId) OR Parent ContentType ($ctParent)"))
    }

    # if the content type doesn't exist, create one
    if ($tWeb.ContentTypes[$ctName] -eq $null) {

        # determine which constructor to use
        if ($ctParent) { # use $ctParent
            $tContentType = New-Object Microsoft.SharePoint.SPContentType($ctParent, $tWeb.ContentTypes, $ctName);
        } else {         # use $ctId
            $tId = New-Object Microsoft.SharePoint.SPContentTypeId($ctId)
            $tContentType = New-Object Microsoft.SharePoint.SPContentType($tId, $tWeb.ContentTypes, $ctName);
        }

        $tContentType.Description = $ctDescription
        $tContentType.Group = $ctGroupName

        $tWeb.ContentTypes.Add($tContentType) | Out-Null
        Write-Output([System.String]::Format("Content Type [{1}] : Adding to Web [{0}]", $tWeb.Url, $ctName))
        $tWeb.Update()
    }

} # Function Ensure_ContentType(...)


Created 2011-10-13
comments powered by Disqus
Login