SharePoint Online: Create a Site Column using PowerShell

Requirement: Create site columns in SharePoint Online.

Understanding Site Columns in SharePoint

Before we create site columns, let’s understand their concept and significance in SharePoint. Site columns provide great re-usability in SharePoint without having to recreate fields every time you need them in lists and libraries. They save a lot of time, especially when you have to standardize columns, create columns with data (such as choice fields), or assign default values to them. Once created at the top-level site, a site column can be utilized in any list or library or even content types throughout your SharePoint site hierarchy (or across site collections with the content type hub).

What is a Site Column in SharePoint?

In SharePoint, a site column is a reusable column definition that can be used across multiple lists and libraries within a site collection. It defines the schema and behavior of a specific piece of metadata, such as the column name, data type, default value, and any additional settings or constraints.

Site columns provide a centralized way to manage and maintain consistency in metadata across your SharePoint environment. By defining site columns at the site collection level, you can ensure that the same column is available and consistently applied to lists and libraries throughout the site collection.

Site Columns vs. List Columns

It’s important to understand the distinction between site columns and list columns in SharePoint. While site columns are defined at the site collection level and can be reused across multiple lists and libraries, list columns are specific to a particular list or library and are not reusable across the site collection.

List columns are created within the context of a single list or library and are useful for capturing metadata that is unique to that specific list or library. On the other hand, site columns are designed for metadata that is common and reusable across multiple lists and libraries.

The Advantages of Using Site Columns

  1. Consistency and Reusability: By defining a column once and using it in multiple locations, you ensure data is consistent across your site.
  2. Ease of Management: Update a site column in one place, and all instances automatically inherit the changes.
  3. Improved Searchability: Uniform columns across lists and libraries enhance SharePoint’s search capabilities, making content easier to find.

Think of site columns as building blocks that ensure consistency, reduce redundancy, and simplify content management across your site collections.

Types of Site Columns

SharePoint provides a wide range of site column types to accommodate various data requirements. Let’s explore some of the commonly used site column types:

  1. Single Line of Text: Allows users to enter a single line of text, such as a title or name.
  2. Multiple Lines of Text: Enables users to enter multiple lines of text, such as a description or comments.
  3. Choice: Presents users with a dropdown list of predefined choices.
  4. Number: Accepts numerical values, such as integers or decimals.
  5. Currency: Allows users to enter monetary values.
  6. Date and Time: Captures date and time values.
  7. Lookup: Establishes a relationship between lists by allowing users to select a value from another list.
  8. Yes/No: Represents a boolean value, such as true or false.
  9. Person or Group: Allows users to select one or more users or groups from the SharePoint user directory.
  10. Managed Metadata: Enables users to select values from a hierarchical term set.

Each site column type has its own set of properties and behaviors that can be configured to meet specific requirements. Now that we have a solid understanding of site columns and their types, let’s explore the different methods to create site columns in SharePoint Online.

Site Column Practical Example

Let’s say you use SharePoint Online for project management in your organization. You create a site column named “Project Status” of type “Choice” with options like “Not Started,” “In Progress,” “On Hold,” and “Completed.” This site column is then added to various lists and libraries across the project site, allowing team members to track and report the status of project-related items consistently!

How to Create a Site Column in SharePoint Online?

Site columns are a powerful tool in SharePoint Online that allows you to define and reuse metadata across lists, libraries, and content types. This blog post will show you how to create a site column in SharePoint Online. They are a great way to standardize the data stored in your lists and libraries and make finding and using information easier. Let’s get started!

To create a site column in SharePoint Online, follow these steps:

  1. Login to SharePoint Online site. Click on Site Settings Gear and select Site Settings.
  2. On the Site Settings page, click on the “Site Columns” link under the “Web Designer Galleries” group. This page lists all available site columns.
  3. On the Site Columns page, click on the “Create” link at the top. sharepoint online powershell create site column
  4. In create column page, Enter the name for your site column. Select the column type, and specify additional column settings specific to the new site column. Select the existing group or new group for your site column. Click on the “OK” button at the bottom to complete creating the site column in SharePoint Online.
    create site columns using powershell in sharepoint online

The site column will now be added to the site. After creating a site column, it can be added to any list or library on your site.

Create Site Columns using PowerShell in SharePoint Online:

Let’s see how to create a site column in SharePoint Online using PowerShell. Here is my collection of PowerShell scripts to create site columns in SharePoint Online using the client-side object model (CSOM).

Important: Field Schema XML is case-sensitive!

Create a Single Line of Text Site Column in SharePoint Online using PowerShell

PowerShell provides a powerful and efficient way to programmatically create site columns in SharePoint Online. Here is the SharePoint Online PowerShell to add a site column:

#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"
 
#Parameters
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectCode"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

Try {
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Get all Site columns from the site
    $Fields = $Ctx.web.Fields
    $Ctx.Load($Fields)
    $Ctx.executeQuery()

    #Check if the column name exists
    $NewField = $Fields | where {$_.Title -eq $ColumnName}
    if($NewField -ne $NULL)  
    {
        Write-host "Site Column $ColumnName already exists!" -f Yellow
    }
    else
    {
        #Define XML for Field Schema
        $FieldSchema = "<Field Type='Text' DisplayName='$ColumnName' Name='$ColumnName' required='$IsRequired' Group='$ColumnGroup'/>"
        $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
        $Ctx.ExecuteQuery()    

        Write-host "Site Column Created Successfully!" -ForegroundColor Green  
    }
}
Catch {
    write-host -f Red "Error Creating Site Column!" $_.Exception.Message
}

Add Multiple Lines of Text Field using PowerShell

This time, let’s wrap the code into a reusable function:

#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"

#Custom function to add Multiline Text Field
Function Add-MultilineSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,        
        [Parameter(Mandatory=$true)] [string] $NumberofLines,
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $RichText,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists
        $NewField = $Fields | where {$_.Title -eq $ColumnName}
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Note' ID='{$FieldID}' DisplayName='$ColumnName' Name='$ColumnName' RichText='$RichText' Required='$IsRequired' Group='$ColumnGroup'/>"
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Define value for parameters
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectDescription"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"
$RichText ="FALSE"
$NumberofLines="5"

#Call the function to create Multiline site column
Add-MultilineSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -IsRequired $IsRequired -NumberofLines $NumberofLines -RichText $RichText -ColumnGroup $ColumnGroup

PowerShell to Create Person or Group (People Picker) Site Column to SharePoint Online:

#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"

#Custom function to add site column
Function Add-PersonOrGroupSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,             
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists already
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='User' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup' ShowField='ImnName' List='UserInfo' UserSelectionMode='PeopleOnly' />"
            $FieldSchema
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectMembers"
$ColumnDisplayName="Project Members"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-PersonOrGroupSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup 

Add Date and Time Site Column to SharePoint Online:

#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"

#Custom function to add site column
Function Add-DateTimeSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
        [Parameter(Mandatory=$true)] [string] $Format,        
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists already
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='DateTime' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Format='$Format' Required='$IsRequired' Group='$ColumnGroup'/>"
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectStartDate"
$ColumnDisplayName="Project Start Date"
$Format="DateOnly"
$IsRequired = "FALSE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-DateTimeSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -Format $Format -ColumnGroup $ColumnGroup

PowerShell CSOM script to Add Currency Site Column for SharePoint Online

#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"

#Custom function to add site column
Function Add-CurrencySiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
         [Parameter(Mandatory=$true)] [string] $LCID,        
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists already
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Currency' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' LCID='$LCID' Required='$IsRequired' Group='$ColumnGroup'/>"
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="TotalInvestment"
$ColumnDisplayName="Total Investment Amount"
$LCID="1081" #India
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-CurrencySiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -LCID $LCID -ColumnGroup $ColumnGroup

Refer https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splocale.lcid.aspx for all LCIDs.

SharePoint Online: Add Number Site Column with PowerShell

#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"

#Custom function to add site column
Function Add-NumberSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,        
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Number' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup'/>"
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="HeadCount"
$ColumnDisplayName="Head Count"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-NumberSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup

How to Add Choice Site Column to SharePoint Online using PowerShell?

#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"

#Custom function to add site column
Function Add-ChoiceSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
        [Parameter(Mandatory=$true)] [string] $ChoiceValues,        
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Fields = $Ctx.web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists already
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Frame Choices
            $ChoiceOptions=[string]::Empty
            $Choices = $ChoiceValues.Split(",")
            foreach ($Choice in $Choices)
            {
                $ChoiceOptions = $ChoiceOptions + "<CHOICE>$Choice</CHOICE>"
            }
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Choice' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup'> <CHOICES>$ChoiceOptions</CHOICES></Field>"
            $FieldSchema
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ProjectDepartment"
$ColumnDisplayName="Project Department"
$IsRequired = "TRUE"
$ChoiceValues="IT,Sales,Operations,Marketing,HR"
$ColumnGroup="Crescent Projects"

#Call the function to create site column
Add-ChoiceSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ChoiceValues $ChoiceValues -ColumnGroup $ColumnGroup

You can also add Type=”MultiChoice”, and Format=”RadioButtons” to customize it further.

Create a Lookup Site Column in SharePoint Online using PowerShell:

#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"

#Custom function to add site column
Function Add-LookupSiteColumn()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$true)] [string] $ColumnDisplayName,
        [Parameter(Mandatory=$true)] [string] $LookupListName,
        [Parameter(Mandatory=$true)] [string] $LookupField,
        [Parameter(Mandatory=$true)] [string] $IsRequired,
        [Parameter(Mandatory=$true)] [string] $ColumnGroup
    )

    #Generate new GUID for Field ID
    $FieldID = ([GUID]::NewGuid()).GUID

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get all Site columns from the site
        $Web = $Ctx.web
        $Ctx.Load($Web)
        $Fields = $web.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()

        #Check if the column name exists already
        $NewField = $Fields | where { ($_.Internalname -eq $ColumnName) -or ($_.Title -eq $ColumnDisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Site Column $ColumnName already exists!" -f Yellow
        }
        else
        {
            #Get IDs of Lookup List and Web
            $LookupList=$Web.Lists.GetByTitle($LookupListName)
            $Ctx.Load($LookupList)
            $Ctx.executeQuery()

            $LookupListID= $LookupList.id
            $LookupWebID=$Ctx.web.Id

            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Lookup' ID='{$FieldID}' DisplayName='$ColumnDisplayName' Name='$ColumnName' Required='$IsRequired' Group='$ColumnGroup' List='$LookupListID' WebId='$LookupWebID' ShowField='$LookupField' />"
            $NewField = $Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
            $Ctx.ExecuteQuery()    

            Write-host "Site Column Created Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Creating Site Column!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ColumnName="ParentProject"
$ColumnDisplayName="Parent Project"
$IsRequired = "TRUE"
$ColumnGroup="Crescent Projects"
$LookupList="Projects" #Parent Lookup
$LookupField="ProjectName"

#Call the function to create site column
Add-LookupSiteColumn -SiteURL $SiteURL -ColumnName $ColumnName -ColumnDisplayName $ColumnDisplayName -IsRequired $IsRequired -ColumnGroup $ColumnGroup -LookupList $LookupList -LookupField $LookupField

Refer to this MSDN article to frame schema XML attributes for site columns: https://msdn.microsoft.com/en-us/library/office/aa979575.aspx

SharePoint Online PnP PowerShell to Create Site Column

Let me show you how to create a site column in SharePoint Online with PnP PowerShell.

In this example:

  1. We connect to the SharePoint Online admin center using the Connect-PnPOnline cmdlet.
  2. We specify the URL of the site collection where we want to create the site column.
  3. We define the column group, display name, internal name, and column type.
  4. We use the Add-PnPField cmdlet to create the site column, specifying the desired properties.

Creating site columns using PowerShell is particularly useful when you need to create multiple site columns programmatically or automate the provisioning process.

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com"
$ColumnTitle = "Project Name"
$ColumnInternalName = "ProjectName"
$ColumnGroup="Crescent Site Columns"
$ColumnType = "Text"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    
    #Create Site Column
    Add-PnPField -DisplayName $ColumnTitle -InternalName $ColumnInternalName -Group $ColumnGroup -Type $ColumnType
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

To add a choice column with PnP PowerShell, you can use:

#Create a choice Site Column
Add-PnPField -DisplayName "Project Status" -InternalName "ProjectStatus" -Type Choice -Choices "Active", "On-Hold", "Completed"

Refer to the Microsoft documentation https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.client.fieldtype?view=sharepoint-csom for all available field types!

Similarly, you can create site columns from XML schema as:

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Define XML Schema for Text Field
$FieldXML= "<Field Type='Text' Name='ProjectCode' ID='$([GUID]::NewGuid())' DisplayName='Project Code' Required ='FALSE' EnforceUniqueValues = 'TRUE' Indexed='TRUE'></Field>"
 
#Create Single Line of Text site column
Add-PnPFieldFromXml -FieldXml $FieldXML

Site Column Best Practices

To ensure optimal performance, maintainability, and usability of your SharePoint environment, it’s important to follow best practices when working with site columns. Here are a few key considerations:

  1. Use Meaningful Names: Choose clear and descriptive names for your site columns to make their purpose obvious to users.
  2. Group Related Columns: Organize site columns into logical groups to improve discoverability and management.
  3. Avoid Duplication: Before creating a new site column, check if a similar column already exists to prevent duplication and maintain consistency.
  4. Use Appropriate Column Types: Select the most suitable column type based on the nature of the data being captured.
  5. Leverage Managed Metadata: Utilize managed metadata columns to enforce a structured and controlled vocabulary for consistent data entry.
  6. Consider Performance: Be mindful of the number and complexity of site columns, as excessive columns can impact performance and usability.
  7. Document and Communicate: Maintain documentation of your site columns and communicate their purpose and usage guidelines to users.

By following these best practices, you can establish a well-organized and efficient SharePoint environment that promotes data integrity and usability.

Conclusion

Creating site columns is a fundamental skill for any SharePoint administrator or power user. Site columns provide a centralized and reusable way to define and manage metadata across lists and libraries in SharePoint Online. By leveraging site columns effectively, you can ensure data consistency, improve usability, and streamline information management within your SharePoint environment.

In this article, we explored the concept of site columns, their types, and the different methods to create them, including using the SharePoint user interface and PowerShell. We also discussed best practices to follow when working with site columns and provided real-world examples to illustrate their practical applications.

Once the site SharePoint site column is ready, you can add it to your list through the list settings, site columns section. To add an existing site column to the SharePoint Online list or Library, use: How to Add a Site Column to the SharePoint Online List?

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *