Provision

Create Library and add custom Content Type

Script to create SharePoint document library and add custom content type

Summary

This sample script creates a SharePoint document library by checking whether it exists or not. Adds custom content type to the document library and makes it as a default content type.

powershell

function CreateLibraryWithCT {
    param ([string] $LibraryName)

    $ctName = "My Custom CT"
    $libExist = Get-PnPList $LibraryName -ErrorAction SilentlyContinue
    if ($libExist) {
        Write-Host "Library - $LibraryName already exists" -ForegroundColor Yellow
    }
    else {
        #Creating library with Document library template
        New-PnPList -Title $LibraryName -Template DocumentLibrary
        Write-Host "Created Library: " $LibraryName -ForegroundColor Green
    }

    $ctExist = Get-PnPContentType $ctName -ErrorAction SilentlyContinue
    if ($ctExist) {
        Write-Host "Content type - $ctName already exists" -ForegroundColor Yellow
    }
    else {
        $ctExist = Add-PnPContentType -Name $ctName `
            -Group "Custom Content Types" `
            -Description "My Custom CT description"
        Write-Host "Created Content Type: " $ctName -ForegroundColor Green
    }

    #region Adding, setting default content type and remove existing CT
    Add-PnPContentTypeToList -List $LibraryName -ContentType $ctExist
    Set-PnPDefaultContentTypeToList -List $LibraryName -ContentType $ctName
    Remove-PnPContentTypeFromList -List $LibraryName -ContentType "Document"
    #endregion
}

try {
    $clientId = ""
    $clientSecret = ""
    $siteUrl = "https://contoso.sharepoint.com/sites/PnPPowerShell"
    Connect-PnPOnline -Url $siteUrl -ClientId $clientId -ClientSecret $clientSecret

    CreateLibraryWithCT -LibraryName "My Lib"
}
catch {
    Write-Error "Something wrong: " $_
}
finally {
    $pnpConnection = Get-PnPConnection -ErrorAction SilentlyContinue
    if ($pnpConnection) {
        Disconnect-PnPOnline
    }
}

Contributors

Author(s)
Ahamed Fazil Buhari
Ganesh Sanap

Disclaimer

THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Tool documentation & references

Keep exploring