Saturday, October 8, 2016

SharePoint Online: Check If Field Exists in List using PowerShell

Requirement:
PowerShell to check if a field exists in list in SharePoint online.

SharePoint Online - PowerShell to check if a Column exists in List

#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 Check if a column exists in a List
Function Check-ColumnExists($SiteURL, $ListName, $FieldName, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Retrive all Fields from the list
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Fields = $List.Fields
    $Ctx.Load($List)
    $Ctx.Load($Fields)
    $Ctx.ExecuteQuery()

    #Check if the given field name 
    $Field = $Fields | where{$_.Title -eq $FieldName}
    if($Field)  { return $true } else { return $false}
}

#Set Variables for Site URL, List Name and Column Name
$URL= "https://crescent.sharepoint.com/sites/sales/"
$List="Project Documents"
$Field="Department" #Display Name

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check Column Exists in given list
$ColumnExists = Check-ColumnExists -SiteURL $URL -ListName $List -FieldName $Field -Credentials $Cred

if($ColumnExists) {
    write-host "Column Exists in Given List!" -f Green
    #Proceed with your script
 }
 else {
    write-host "Column Doesn't Exists in given List!" -f Red
 }



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!


You might also like:

Related Posts Plugin for WordPress, Blogger...