How to create SharePoint Document Library and create columns using PowerShell

Chung Man 20 Reputation points
2024-05-24T06:45:36.7+00:00

Hi there, I am new to using PowerShell to create SharePoint. May I know where can I find the relevant script to create a document library and create column accordingly?

Appreciated.

Note:

I searched some script but unsure if the building block makes sense to create the library document and add its relevant column by PowerShell..:

#1. PowerShell to create modern site collection

Function Create-SPOSite

{

param

(

    [string]$Title  = $(throw "Please Provide the Site Title!"),

    [string]$URL = $(throw "Please Provide the Site URL!"),

    [string]$Owner = $(throw "Please Provide the Site Owner!"),

    [int]$StorageQuota = $(throw "Please Provide the Site Storage Quota!")

)

#Connection parameters

$AdminURL = "https://crescent-admin.sharepoint.com"

$AdminName = "SpAdmin@crescent.com"

Try{

#Connect to Office 365

Connect-SPOService -Url $AdminURL -Credential (Get-Credential)



#Check if the site collection exists already

$SiteExists = Get-SPOSite | Where {$_.URL -eq $URL}

 

#Check if the site exists in the recycle bin

$SiteExistsInRecycleBin = Get-SPODeletedSite | where {$_.url -eq $URL}



If($SiteExists -ne $null)

{

    write-host "Site $($url) exists already!" -foregroundcolor Yellow

}

elseIf($SiteExistsInRecycleBin -ne $null)

{

    write-host "Site $($url) exists in the recycle bin!" -foregroundcolor Yellow

}

else

{

    #sharepoint online create modern site collection powershell

    New-SPOSite -Url $URL -title $Title -Owner $Owner -StorageQuota $StorageQuota -NoWait -ResourceQuota $ResourceQuota -Template $Template

    write-host "Site Collection $($url) Created Successfully!" -foregroundcolor Green

}

}

catch {

write-host "Error: $($_.Exception.Message)" -foregroundcolor Red

}

}

#Parameters to create new site collection

$SiteTitle = "Purchase"

$SiteURL= "https://crescent.sharepoint.com/sites/purchase"

$SiteOwner = "spsadmin@crescent.com"

$StorageQuota = 2048

$SiteTemplate = "STS#3"

#Call The function to create site collection in SharePoint Tenant

Create-SPOSite -Title $SiteTitle -URL $SiteURL -Owner $SiteOwner -StorageQuota $StorageQuota -Template $SiteTemplate

#Read more: https://www.sharepointdiary.com/2019/07/create-modern-site-in-sharepoint-online-using-powershell.html#ixzz8b7oO2Vh9

#2 Use the New-SPOList cmdlet to create a new document library. You can specify the library name, description, and other settings as parameters.

#Example: New-SPOList -Title "My Document Library" -Template DocumentLibrary

#3 Use the Add-SPOField cmdlet to add a new column to the library. You can specify the column name, type, and other settings as parameters.

#Example: Add-SPOField -List "My Document Library" -DisplayName "My Column" -Type Text

SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,784 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,274 questions
0 comments No comments
{count} votes

Accepted answer
  1. RaytheonXie_MSFT 33,251 Reputation points Microsoft Vendor
    2024-05-24T08:32:02.8166667+00:00

    Hi @Chung Man,

    To create a sharepoint library, you could use following script

    #Load SharePoint CSOM Assemblies
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
     
    #Variables for Processing
    $SiteURL = "https://Crescent.sharepoint.com/Sites/Sales"
    $LoginName ="Salaudeen@Crescent.OnMicrosoft.com"
    $LoginPassword ="Password"
     
    #Get the Client Context
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
     
    #supply Login Credentials
    $SecurePWD = ConvertTo-SecureString $LoginPassword -asplaintext -force 
    $Credential = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($LoginName,$SecurePWD)
    $Context.Credentials = $Credential
     
    #powershell create document library sharepoint online
    $ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
    $ListInfo.Title = "Project Docs"
    $ListInfo.TemplateType = 101 #Document Library
    $List = $Context.Web.Lists.Add($ListInfo)
    $List.Description = "Repository to store project artifacts"
    $List.Update()
    $Context.ExecuteQuery()
     
    write-host "New Document Library has been created!"
    

    If you want to add columns to the list, you could use following script

    #Load SharePoint CSOM Assemblies
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
     
    #Set parameters
    $SiteURL="https://salaudeen.sharepoint.com/sites/Retail"
    $ListName="Projects"
    $Name="ProjectCode"
    $DisplayName="Project Code"
    $Description="Enter the Project Code"
    $IsRequired = "TRUE"
    $EnforceUniqueValues="FALSE" #Must set Indexed="FALSE", if Unique="TRUE"
    $MaxLength="100"
      
    #Generate new GUID for Field ID
    $FieldID = New-Guid
      
    Try {
        #Get Credentials to connect
        $Cred= Get-Credential
      
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
              
        #Get the List
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $Ctx.ExecuteQuery()
      
        #Check if the column exists in list already
        $Fields = $List.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()
        $NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
        if($NewField -ne $NULL) 
        {
            Write-host "Column $Name already exists in the List!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Text' ID='{$FieldID}' Name='$Name' StaticName='$Name' DisplayName='$DisplayName' Description='$Description' Required='$IsRequired' EnforceUniqueValues='$EnforceUniqueValues' MaxLength='$MaxLength' />"
            $NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
            $Ctx.ExecuteQuery()   
      
            Write-host "New Column Added to the List Successfully!" -ForegroundColor Green 
        }
    }
    Catch {
        write-host -f Red "Error Adding Column to List!" $_.Exception.Message
    }
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful