SharePoint Online: Find Site Column Usage in Content Types using PowerShell
Requirement: Find Site Column Usage in Content Type in SharePoint Online site collection.
A little background: When trying to delete a site column in SharePoint Online, got an error message: “site columns which are included in content types cannot be deleted. Remove all references to this site column prior to deleting it”.
So, How to find where a site column is being used?
PowerShell to Find Site Column usage in Content Types:
This PowerShell script loops through all content types in the site, checks if the particular site column is referenced in any of them, and outputs the result.
#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"
#Function to get a particular Site column usage in content types
Function Get-SPOSiteColumnUsage([String]$SiteURL, [String]$SiteColumnInternalName)
{
Try{
Write-host -f Yellow "Processing Site:" $SiteURL
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get All Content Types of the Web
$Ctx.Load($Ctx.Web)
$Ctx.Load($Ctx.Web.Webs)
$ContentTypes = $Ctx.web.ContentTypes
$Ctx.Load($ContentTypes)
$Ctx.ExecuteQuery()
#Leave Hidden content types
$ContentTypes = $ContentTypes | Where {$_.Group -ne "_Hidden"}
Write-host -f Yellow "`t Found $($ContentTypes.count) Content Types"
#Loop through each content types Field
ForEach($ContentType in $ContentTypes)
{
Write-host -f Yellow "`t `t Scanning Content Type $($ContentType.Name)"
$Ctx.Load($ContentType.Fields)
$Ctx.ExecuteQuery()
ForEach($Field in $ContentType.Fields)
{
If($Field.InternalName -eq $SiteColumnInternalName)
{
Write-host -f Green "`t `t Found the Site Column in Content Type '$($ContentType.Name)' at Site '$($SiteURL)'"
}
}
}
#Iterate through each subsite of the current web
foreach ($Subweb in $Ctx.web.Webs)
{
#Call the function recursively
Get-SPOSiteColumnUsage $Subweb.url $SiteColumnInternalName
}
}
Catch {
write-host -f Red "Error Generating Site Column Usage Report!" $_.Exception.Message
}
}
#Config Parameters
$SiteURL="https://crescent.sharepoint.com"
$SiteColumnInternalName="TotalInvestment"
#Get Credentials to connect
$Cred= Get-Credential
#Call the function to get the content type usage
Get-SPOSiteColumnUsage $SiteURL $SiteColumnInternalName
This script scans all content types and prints the results:
wow intelligent way of using Recursive. Bravo.. Thank you so much for this saved lot of time.