Created
June 1, 2015 15:00
-
-
Save asadrefai/65092af31591b6a009ef to your computer and use it in GitHub Desktop.
Check if field exists in a SharePoint list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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