ps-updatelistitemscamlquery

Title:  Update List items on Conditional based using CAML Query

  1. Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"  
  2. Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
  3.     
  4.   
  5. $SiteURL="https://hpeblore.sharepoint.com/sites/Omi"  
  6. $ListName="Employee"  
  7.    
  8. Try {  
  9.     $Cred= Get-Credential  
  10.     $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)  
  11.   
  12.     #Setup the context  
  13.     $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  
  14.     $Ctx.Credentials = $Credentials  
  15.     $Web = $Ctx.web  
  16.   
  17.     #Get and load the List     
  18.     $List = $Ctx.Web.Lists.GetByTitle($ListName)  
  19.     $Ctx.Load($List)  
  20.     $Ctx.ExecuteQuery()  
  21.   
  22.     #Get Selected  List items  
  23.     $CAMLQuery = New-Object Microsoft.SharePoint.Client.CamlQuery  
  24.     #$CAMLQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>Bramhendra</Value></Eq></Where></Query></View>"  
  25.     $CAMLQuery.ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>Bramhendra</Value></Eq><Eq><FieldRef Name='Location' /><Value Type='Text'>Bangalore</Value></Eq></And></Where></Query></View>"  
  26.    # yyyy-MM-dd #  <FieldRef Name='DOJ' /><Value IncludeTimeValue='TRUE' Type='DateTime'>2018-04-13</Value>  
  27.     
  28.     $ListItems = $List.GetItems($CAMLQuery)  
  29.     $Ctx.Load($ListItems)  
  30.     $Ctx.ExecuteQuery()  
  31.     Write-host $ListItems.Count  
  32.   
  33.    if( $ListItems.Count -gt 1)  
  34.    {  
  35.    write-host "Many items found for "  
  36.    }  
  37.    elseif( $ListItems.Count -eq 1)  
  38.    {  
  39.       
  40.     Foreach ($ListItem in $ListItems) # it loops only above filter item  
  41.     {  
  42.           
  43.         if($ListItem["Title"] -eq "Bramhendra" -and $ListItem["Location"] -eq "Bangalore")   # add if dropaccount=SVC_Sharepoint  
  44.         {  
  45.         $ListItem["Location"] = "Bangalore2"  
  46.         #write-host $ListItem["ID"]  
  47.         $ListItem.Update()  
  48.         $Ctx.ExecuteQuery()  
  49.         }  
  50.     }  
  51.     }  
  52.     else   
  53.     {write-host " items not  found"}  
  54.        
  55.     }  
  56. Catch {  
  57.     write-host -f Red "Error Updating List Items!" $_.Exception.Message  
  58. }