Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Created June 1, 2015 15:00
Show Gist options
  • Save asadrefai/65092af31591b6a009ef to your computer and use it in GitHub Desktop.
Save asadrefai/65092af31591b6a009ef to your computer and use it in GitHub Desktop.
Check if field exists in a SharePoint list
function Check-ColumnExists()
{
param(
[Parameter(Mandatory=$true)][string]$url,
[Parameter(Mandatory=$true)][System.Net.NetworkCredential]$credentials,
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string]$fieldName
)
begin{
try
{
#get Client Object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$context.Credentials = $credentials
$web = $context.Web
$context.Load($web)
$context.ExecuteQuery()
#Retrieve List
$List = $Context.Web.Lists.GetByTitle($listName)
$context.Load($List)
$context.ExecuteQuery()
#Retrive Fields
$Fields = $List.Fields
$context.Load($Fields)
$context.ExecuteQuery()
}
catch
{
Write-Host ("Error while getting context. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
process{
try
{
$Field = $List.Fields | where{$_.Title -eq $fieldName}
if($Field)
{
#Execute if Field exists
Write-Host "Field " $fieldName " exists" -ForegroundColor Green
return $true
}
else
{
#Execute if Field does not exists
Write-Host "Field " $fieldName " does not exists" -ForegroundColor Green
return $false
}
}
catch
{
Write-Host ("Error while checking for field. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$context.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment