Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Created August 11, 2015 09:25
Show Gist options
  • Select an option

  • Save asadrefai/1049aa1356571622a777 to your computer and use it in GitHub Desktop.

Select an option

Save asadrefai/1049aa1356571622a777 to your computer and use it in GitHub Desktop.
Add a field to SharePoint custom list using CSOM PowerShell
function Add-FieldToList()
{
param(
[Parameter(Mandatory=$true)][string]$url,
[Parameter(Mandatory=$true)][System.Net.NetworkCredential]$credentials,
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string]$fieldName,
[Parameter(Mandatory=$true)][string]$fieldXml,
[Parameter(Mandatory=$false)][bool]$isExistingField
)
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()
if($isExistingField -eq $true)
{
#Find an existing site column
$field = $Context.Web.AvailableFields | Where {$_.Title -eq $fieldName}
$context.Load($field)
$context.ExecuteQuery()
}
}
catch
{
Write-Host ("Error while getting context. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
process{
try
{
if($isExistingField -eq $true)
{
#Add existing field to the List
$List.Fields.Add($field)
$List.Update()
$context.ExecuteQuery()
Write-Host "Field Added successfully" -ForegroundColor Green
}
else
{
#Add new field to the list
$List.Fields.AddFieldAsXml($fieldXml,$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$List.Update()
$context.ExecuteQuery()
Write-Host "Field Added successfully" -ForegroundColor Green
}
}
catch
{
Write-Host ("Error while adding 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