Skip to content

Instantly share code, notes, and snippets.

@reshmee011
Last active March 17, 2020 06:34
Show Gist options
  • Save reshmee011/7dec75c5206e4c68ded457bf40a3b32e to your computer and use it in GitHub Desktop.
Save reshmee011/7dec75c5206e4c68ded457bf40a3b32e to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory=$true, position=0, ValueFromPipeLineByPropertyName=$true, HelpMessage="Specifies the Web. The type must be a valid URL or GUID")]
[String]$WebUrl
)
Set-Location $PSScriptRoot
Add-Type -Path ( ".\SharePoint Assemblies\Microsoft.SharePoint.Client.dll")
Add-Type -Path ( ".\SharePoint Assemblies\Microsoft.SharePoint.Client.Runtime.dll")
# help to use lamda expressions to query object properties
. .\Load-CSOMProperties.ps1
function Add-ChoiceValueToField {
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true,Position=0)]
[Microsoft.SharePoint.Client.ClientContext]$ctx,
[Parameter(Mandatory=$false, position=1, ValueFromPipeLine=$true, ValueFromPipeLineByPropertyName=$true, HelpMessage="TODO")]
[Alias("ListName")]
[string]$ListTitle,
[Parameter(Mandatory=$false, position=2,ValueFromPipeLineByPropertyName=$true, HelpMessage="TODO")]
[string]$FieldName,
[Parameter(Mandatory=$false, position=3,ValueFromPipeLineByPropertyName=$true, HelpMessage="TODO")]
[Alias("Field")]
[string]$ChoiceValue
)
#Retrieve List
$List = $ctx.Web.Lists.GetByTitle($ListTitle)
$ctx.Load($List)
$ctx.ExecuteQuery()
#Retrieve field
$field = $List.Fields.GetByInternalNameOrTitle($FieldName);
$fieldChoice = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo").MakeGenericMethod([Microsoft.SharePoint.Client.FieldChoice]).Invoke($ctx,$field)
Load-CSOMProperties -object $fieldChoice -propertyNames @("Choices") ;
$ctx.Load( $fieldChoice);
$ctx.ExecuteQuery() ;
#if not exists then add
$bExists = $false
$FieldChoiceValues=@();
foreach ($choice in $fieldChoice.Choices)
{
$FieldChoiceValues +=$choice
if($choice -eq $ChoiceValue)
{
$bExists = $true
}
}
#add choices to dropdown list
if($bExists -eq $false)
{
$FieldChoiceValues += $ChoiceValue
$fieldChoice.Choices = $FieldChoiceValues;
$fieldChoice.Update()
$ctx.ExecuteQuery() ;
}
}
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
# $ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
$web = $ctx.Web
$ctx.Load($web)
$ctx.ExecuteQuery()
Add-ChoiceValueToField -ctx $ctx -ListTitle "ListTestManually" -FieldName "TypeNum" -ChoiceValue "7"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment