CAML Query Using CSOM in PowerShell

Hi,
I am trying to retrieve list items based on certain conditions using CAML query. I am using CAML query in Powershell using CSOM.​ The issue is no matter what condition i provide, it returns all list items. Any help would be highly appreciated. The script is: 
# Location of DLL's
$loc ="C:\SharePoint\ClientDLL"
Write-Host "Date Range"
Set-Location $loc
Add-Type -Path (Resolve-Path Microsoft.SharePoint.Client.dll)
Add-Type -Path (Resolve-Path Microsoft.SharePoint.Client.Runtime.dll)
#Write the path of SharePoint Portal within double braces
$siteUrl = ""
#Login ID
$loginname = ""
#$listname=""
Write-Host "Please enter password for $($siteUrl):"
$pwd = Read-Host -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.Credentials = New-Object System.Net.NetworkCredential($loginname, $pwd)
$web = $ctx.Web
$list=$Web.Lists.GetByTitle($listname)
$count = $list.ItemCount
Write-Host $count
$newline = [environment]::newline
$($list.Title)
Write-Host -NoNewline "Deleting list items from : $($listname)" -foregroundcolor black -backgroundcolor yellow
#$caml="<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>achint</Value></Eq></Where></Query></View>"
$caml="<View><Query><Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>11/9/2014</Value></Eq></Where></Query></View>"
$cquery = New-Object Microsoft.SharePoint.Client.CamlQuery
$cquery.ViewXml=$caml    
$listItems = $list.GetItems($cquery)
$ctx.Load($listItems)
$ctx.ExecuteQuery()
$newline
Write-Host  $listItems.Count
if ($listItems.Count -gt 0)
        #$listItems | % {$list.GetItemById($_.Id).DeleteObject()}        
        #$ctx.ExecuteQuery()
        Write-Host "All list items deleted from List." -foregroundcolor black -backgroundcolor green
else
        Write-Host "No Item in list: $($listname) to delete" -foregroundcolor black -backgroundcolor red
Regards,
Sudheer
Thanks & Regards, Sudheer

HI?
TRY to use query like this :
$query = "<query>
<where>
<eq>
<FieldRef Name="ID"
<Value Type="Number">$IDNum</value>
</eq>
</where>
</query>"

Similar Messages

  • Caml query using managed metadata column

    hi,
     I am having a console appln, where i want  to pass the one paramater in the form of siteCol1:subsite1:subsite2  where  siteCol1:subsite1:subsite2 is the path of subsite which is in MMS.
    Can i pass this string paramter to the splist which contains a taxonomy column   and match this paramter in the listitemcollection and fetch only those recordw which matches this crirteria.
    and it should fetch the values which matches in a splist. the caml query it expects contains the taxonomy -managed metadata column - , but i am stuck with
    SPList splistLIST = parenttWeb.Lists.TryGetList("LIST1");
                          if ((splistLIST.Items.Count > 0 && splistLIST!= null))
                              SPQuery   objnodeQuery = new SPQuery();
                              objnodeQuery.Query =
                                  string.Format(
           "<OrderBy>" +
              "<FieldRef Name='ID' />" +
           "</OrderBy>" +
           "<Where>" +
              "<Eq>" +
                 "<FieldRef Name='myTaxonomy' />" +
                 "<Value Type='Text'>{0}</Value>" +
              "</Eq>" +
           "</Where>", _mcurrentPathTermSet);
                              SPListItemCollection nodeItemCollection = splistLIST1.GetItems(objnodeQuery);
    am not able to retrieve the listitems which passes this as a parameter and retrieve those records where it matches this taxonomy column.
    my doubt is, how to pass a string parameter to the splist contains taxonomy column and fetch those records

    Hi,
    Managed metada column does not supported in lookup column as the thread below:
    https://social.technet.microsoft.com/Forums/en-US/0dee5ba4-9648-445f-a774-8c59cf01b81c/confirmation-needed-cant-lookup-managed-metadata-field-with-lookup-column?forum=sharepointgeneralprevious
    If you prefer managed metadata in Search, then I'd suggest you find workaround to use managed metadata column in lookup column. You could use a workflow to copy the managed metadata column to a text field, make the text field to be hidded from the list if
    necessary. Then lookup this text field in other list.
    Regards,
    Rebecca Tu
    TechNet Community Support

  • GetListItems CAML query using Lookup fields

    Hi,
    I am struggling to find the correct CAML query syntax to use for GetListItems where I need to return an item ID based on a query involving both a lookup field (lookup is to a column within the same list) and a text field.
    For Example (but changing one of the below to a lookup field):-
    <soap:Body>
        <m:GetListItems>
          <m:listName>ListName</m:listName>
          <m:query>
    <Query>
      <Where>
        <And>
          <Eq>
            <FieldRef Name="LevelOne" />
            <Value Type="Text">"test1"</Value>
          </Eq>
          <Eq>
            <FieldRef Name="LevelTwo' />
            <Value Type="Text">"test2"</Value>
          </Eq>
        </And>
      </Where>
    </Query>
    </m:query>
    <m:viewFields>
    <FieldRef Name ="ID" />
    </ViewFields>
    </m:viewFields>
    </m:GetListItems>
    </soap:Body>
    Any help appreciated!

    When you query a lookup column, you can choose to either query by text value or by lookup ID number (that is, the ID of the item being looked up).
    Here are examples of both:
    <FieldRef Name="MyLookupColumn" />
    <Value Type="Lookup">Thriggle</Value>
    <FieldRef Name="MyLookupColumn" LookupId="TRUE" />
    <Value Type="Lookup">100</Value>

  • Fetch Data through Caml Query using textboxes as parameters

    Hi All,
           *I am very new to SharePoint and working on SharePoint dev.I have task to get the list items based on 2 conditions and I am passing parameters as texboxes to get the data dynamically .
         *I had written the below code(Code 1) for which it is showing me errors and Code2 is working fine.Can any one help me what is error
    Code 1
      SPList mylist = myweb.Lists["Manager"];
                    SPItem myitem = mylist.Items.Add();
                    SPQuery myquery = new SPQuery();
                    string idvalue = txtid.Text.ToString();
                    //myquery.Query = @"<Where><Eq><FieldRef Name='ID'/><Value Type='Number'>"+txtid.Text.ToString()+"</Value> </Eq></Where>";
                    string idvaluuue=txtid.Text.ToString();;
                    myquery.Query = @"<Where>
                  <And>
                      <Eq>
                         <FieldRef Name='ID'/>
                         <Value Type='Number'>"+idvaluue+"</Value>
                      </Eq>
                       <Eq>
                         <FieldRef Name='NumberOfEvents'/>
                         <Value Type='Text'>"+drbcalenders.SelectedItem.Text.ToString()+"</Value>
                       </Eq>
                   </And>
                  </Where>";
    Code 2
    SPList mylist = myweb.Lists["sample"];
                    SPItem myitem = mylist.Items.Add();
                    SPQuery myquery = new SPQuery();
                    string idvalue = txtid.Text.ToString();
                    //myquery.Query = @"<Where><Eq><FieldRef Name='ID'/><Value Type='Number'>"+txtid.Text.ToString()+"</Value> </Eq></Where>";
                    string idvaluuue=txtid.Text.ToString();;
                    myquery.Query = @"<Where>
                  <And>
                      <Eq>
                         <FieldRef Name='ID'/>
                         <Value Type='Number'>9</Value>
                      </Eq>
                       <Eq>
                         <FieldRef Name='NumberOfEvents'/>
                         <Value Type='Text'>July</Value>
                       </Eq>
                   </And>
                  </Where>";
    Samar

    below is query with multiple AND usage...I hope it will help you out...
    string four = "4";
    string five = "5";
    string fifty = "50";
    myQuery.Query = @"<Where>
    <And>
    <And>
    <Eq>
    <FieldRef Name='PCurrency' />
    <Value Type='Currency'>"+fifty+@"</Value>
    </Eq>
    <Eq>
    <FieldRef Name='PNumber' />
    <Value Type='Number'>"+four+@"</Value>
    </Eq>
    </And>
    <Eq>
    <FieldRef Name='ID' />
    <Value Type='Counter'>"+five+@"</Value>
    </Eq>
    </And>
    </Where>";
    ***If my post is answer for your query please mark as answer***
    ***If my answer is helpful please vote ***

  • Join two list with condition using caml query in SharePoint 2013 with client object model

    Hi,
    Want to join two list to get all fields from both list.
    Am new to sharepoint and sharepoint 2013. Am working in sharepoint 2013 online apps. Am using context.executeQueryasync to load list and get items from list. Am able to get items from single list with caml query, but not able to get both list field values
    with joins.  I did lot of surfing..but not..
    Below is my code..
    ListName1 : "AssignedTasks"
    ListName2 : "Tasks"
     var assignedQueryTest = "<View><Joins><Join Type='INNER' ListAlias='Tasks'><Eq><FieldRef Name='TaskId' RefType='Id'/><FieldRef List='Tasks' Name='ID' /></Eq></Join></Joins>"
                    + "<ViewFields><FieldRef Name='TitleValue' /><FieldRef Name='ActionItemsValue' /></ViewFields>"
                    + "<ProjectedFields>"
                    + "<Field Name='TitleValue' Type='Lookup' List='Tasks' ShowField='Title' /><Field Name='ActionItemsValue' Type='Lookup' List='Tasks' ShowField='ActionItems' />"
                    + "</ProjectedFields>"
                    + "</View>";
                   var web = context.get_web();
                    var list = web.get_lists().getByTitle("AssingedTasks");
                    var myQuery = new SP.CamlQuery();
                    myQuery.set_viewXml(assignedQueryTest);
                    var myItems = list.getItems(myQuery, "Include(TitleValue,ActionItemsValue)");
                    context.load(myItems);
                    context.executeQueryAsync(function () { if(myItems.get_count()>0){....}
    }, errorCallback);
    Here am able to get "AssignedTasks" list field values but not able to get "Tasks" list field values. 
    Can you please help me to resolve the issue. Or new idea for join. I have add the condition also in the query.
    If anybody have good sample, please provide.
    Thanks,
    Pariventhan
    Pariventhan.S

    Hi Pariventhan,
    I don't know about join but I have a workaround of this problem.
    Declare one variable (itemcollection) globally. Load all the items "AssignedTasks" using context.load.
    In the success method call another CAML query using <IN> tag of the ID of the items from the second list (Assuming you have look-up column of the ID of the first list to the second list).
    If this is not clear to you then please let me know. If possible then I can provide code sample.
    Thanks,
    Aniruddha

  • Caml Query.

    I have generated a caml query using caml bulider.
    but when i use the same query in my code its is not working and when  i test it in caml query builder tool it worked fine.
    Can anyone help me on this...
    Below is the caml query:
    <Query>
       <Where>
          <And>
             <Eq>
                <FieldRef Name="Status" />
                <Value Type="Text">Passed</Value>
             </Eq>
             <Eq>
                <FieldRef Name="Created" />
                <Value Type="DateTime">[Today-1Day(s)]</Value>
             </Eq>
          </And>
       </Where>
    </Query>

    Are you getting an error or just different results than you expect? I will say that I generally nest my queries a little differently, for instance in your case I would do:
    <Where>
    <And>
    <Eq><FieldRef Name='Created' /><Value Type='DateTime'><Today OffsetDays='-1'/></Value></Eq>
    <Or>
    <Eq><FieldRef Name='xyz' /><Value Type='Lookup'>Passed</Value></Eq>
    <Eq><FieldRef Name='xyz' /><Value Type='Lookup'>Failed</Value></Eq>
    </Or>
    </And>
    </Where>
    Danny Jessee
    MCPD - SharePoint Developer 2010
    MCTS - SharePoint 2010, Configuring
    dannyjessee.com/blog

  • I want to write a CAML query on Id based on Ascending and Descending.

    Hi,
    i want to write a CAML query on Id based on Ascending and Descending.
    Can i write CAML query using both Ascending and Descending?
    Actually my requirement is if i changed the id, Ascending and Descending will perform based on this id.

    Hi,
    Do you want to retrieve a set of items which are sorted based on the value of the ID column using CAML query statement?
    If this is the case, you can compose and test the CAML query statement with the help of
    CAML Designer which with a Graphic User Interface provided:
    http://karinebosch.wordpress.com/my-articles/caml-designer-for-sharepoint-2013/
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • Retrieve All records and display in Report using CAML query in Report Builder if Parameter value is blank

    Hello Experts,
    i have created a report where i have one parameter field where user will pass parameter(e.g. EmpId). As per parameter record will fetched to report if no parameter is passed then it will display all records. I have done it by taking SqlServer Database as datasource.
    by using Following method
    Now i would like to do it by taking Sharepoint List as Datasource. For that what would be the CAML Query.
    Here is my existing CAML query.
    <RSSharePointList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <ListName>Employees</ListName>
      <ViewFields>
        <FieldRef Name="Title" />
        <FieldRef Name="FirstName" />
        <FieldRef Name="LastName" />
        <FieldRef Name="FullName" />
        <FieldRef Name="UserName" />
        <FieldRef Name="Company" />
      </ViewFields>
      <Query>
        <Where>  
    <Eq> 
        <FieldRef Name="Title" />
      <Value Type="Text">    
       <Parameter Name="EmployeeId"/>    
    </Value>
    </Eq>                  
        </Where>
      </Query>
    </RSSharePointList>
    The above code is working if i am passing an employeeId to Parameter. If nothing is passed, it is Not retrieving any record.
    Please suggest
    Thank you
    saroj
    saroj

    Your problem follows the well-established pattern of using an "All" parameter filter in SSRS. There are a few approaches depending on the size of your data. The easiest one is to return all data from CAML and then filter it within SSRS, the following thread
    provides some examples,
    http://stackoverflow.com/questions/18203317/show-all-records-some-records-based-on-parameter-value.
    Other options include passing all of the possible values within the CAML query when "All" is selected, using multiple Report Files to distinguish between both CAML queries, or to use multiple datasets with some logic to show/hide the correct one.
    Dimitri Ayrapetov (MCSE: SharePoint)

  • Sum and group by using CAML query

    Is there any way to get the SUM of values with group by ID using CAML query?
    I have a custom list, in that I have ID and Value columns as below
          ID         Value1      Value2
          1             10             4
          2              5              3
          1             15             2
          3             20             1
    I want to get result:
         ID          Value1        Value2
         1             25                6
         2             5                  3
         3             20                1
    I used CAML query:
    <View>
    <Query>
    <Where>
    <IsNotNull>
    <FieldRef Name="ID" />
    </IsNotNull>
    </Where>
    <GroupBy Collapse="FALSE">
    <FieldRef Name="ID" />
    </GroupBy>
    </Query>
    <ViewFields>
    </ViewFields>
    <Aggregations Value="On">
    <FieldRef Name="Value1" Type="SUM" />
    <FieldRef Name="Value2" Type="SUM" />
    </Aggregations>
    </View>
    But
    this query returns all the records
    that satisfy the condition <Where>.
    I
    do not correctly?

    You need to work with current view based aggregation. Please check below threads for your reference.
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/dda5735a-fecf-403f-9495-1b63617d2fbf/question-on-a-caml-query?forum=sharepointdevelopmentlegacy
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/24e88d6a-ee15-4d81-a5fe-504c7bd14e46/how-to-sum-a-column-value-using-caml-query?forum=sharepointdevelopment
    Hope this helps.
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful
    I've seen these
    issues and articles and do them, but
    does not work. I use object mozhel
    Sharepoint (javascript).

  • Can we query more than 5000 library items in Sharepoint online library using CSOM?

    I am writing a console application to fetch all documents from the SharePoint Online Site. I am worrying what happens if library items grow beyond 5000 items. In my earlier experience from SP2010, I will raise the threshold limit from Central Admin Site
    and then perform my CAML query operation. In SharePoint Online Site, is this possible ? If not, is there any alternative to get all the documents above 5000 limit ?

    At the moment I wouldn't advise it without using folders.
    You can, definitely, add more than 5k items in Office 365 lists. If you design them well and add indexes before you go over the threshold then it should be fine.
    HOWEVER, once you go over the 5k threshold you lose the ability to change all the items in the list at once. Which means you can't add indexes to columns, can't add new columns, can't remove columns or perform any large admin task.
    Incidentally CAML queries and upping the threshold are either/or options in on-premises installs. CAML is the way forward and can be used without increasing the threshold in the vast majority of cases.
    In terms of support the MS documentation is unhelpful:
    http://office.microsoft.com/en-gb/office365-sharepoint-online-enterprise-help/sharepoint-online-software-boundaries-and-limits-HA102694293.aspx
    There it states that MS only support 5k items in a site list/library.

  • Filter SharePoint list items using CAML query as same as Like operator in SQL Server.

    Hi ,
    I have filtered SharePoint list items based on Name using CAML query <Contains> . Now I have a new requirement is to filter list items using Like operator in SQL. But Like operator is not in CAML.
    How do I filter list items using CAML as same as Like operator in SQL.
    Please let me know.
    Thanks in Advance.

    Did you try using <Contains>?
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/15766fd5-50d5-4884-82a1-29a1d5e38610/caml-query-like-operator?forum=sharepointdevelopmentlegacy
    --Cheers

  • Using CAML Query in SharePoint Hosted app

    Hi,
    I am trying to execute a CAML Query in a SharePoint Hosted App, below is the JS code.
        executor.executeAsync({
            url: appwebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Documents')/Items?/getitems?@target='" + hostweburl + "'",
            method: "POST",
        body: { 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, "ViewXml": "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='TEXT'>value</Value></Eq></Where></Query></View>"
        headers: {
            "accept": "application/json; odata=verbose",
            "content-type": "application/json; odata=verbose"
        success: successHandler,
        error: errorHandler
    getting an error: Uncaught Error: "Invalid field or parameter requestInfo.body"

    Are you using rest api?
    Please check this
    http://tech.bool.se/using-caml-sharepoint-rest-api/
    http://msdn.microsoft.com/en-us/library/office/dn531433(v=office.15).aspx

  • Join two list of integer type field using CAML query

    Hi
    As i am struggling in Join two sharepoint list (Roles and Emplyees). As there is no lookup columns and lists are already existing and have almost 3000 + recodrs. As a part of enhancement work need to join these list. List structure is some thing as follows: 
    Roles :
    ID                              Title
    1                               Project Manager
    2                               Business Analyst
    3                              Developer
    Employees :
    Name                       Role
    1 James                  1
    2 Petar                    3
    3 John                     2
    Output should be like as follows:
    Name                       Role
    1 James                  Project Manager
    2 Petar                    Developer
    3 John                     Developer
    So please suggest, if the joining can be done other than lookup columns through the CAML query.
    Akhilesh Rao

    Follow below CAML query to add joins between two lists.
    SPList list = SPContext.Current.Site.RootWeb.Lists["Employees"];
    SPQuery query = new SPQuery();
    query.Joins = @" <Join Type="INNER" ListAlias="Roles">
    <Eq>
    <FieldRef Name="Employees" RefType="Role" />
    <FieldRef List="Roles" Name="ID" />
    </Eq>
    </Join>";
    query.ProjectedFields = @" <Field Name="RoleName" Type="Lookup" List="Roles" ShowField="Title">";
    query.ViewFields = @ "<FieldRef Name="Title">
    <FieldRef Name="RoleName"> ";
    SPListItemCollection result = tablea.GetItems(query);
    Adnan Amin MCT, SharePoint Architect | If you find this post useful kindly please mark it as an answer :)

  • How to sum a column value using CAML Query?

    Hi All,
    I would like to sum the column value using CAML qeury. Actually in my list, I have two column "Projects Name" and "Number of Issues". Now need to get sum of "Number of Issues" column. How to achieve in CAML Query.
    Thanks in advance!

    Hi Sam,
    it looks like you can use your current view based agregation, otherwise it is not possible(
    http://msdn.microsoft.com/en-us/library/ms467521.aspx) and you need to work on custom bit on this requirement.
    use the below link and create a view element as described and see if that works for you
    Aggregations Element
    http://msdn.microsoft.com/en-us/library/ms468626%28v=office.12%29.aspx
    Another reference
    Query Element
    http://msdn.microsoft.com/en-us/library/ms471093.aspx
    Hope this helps!
    Ram - SharePoint Architect
    Blog - SharePointDeveloper.in
    Please vote or mark your question answered, if my reply helps you

  • CAML Query help using recursiveall and date filter together

    Hello,
    Please let me know what is wrong with the query below,
    <View Scope='RecursiveAll'>
    <Query>
    <Where>
    <Leq>
    <FieldRef Name='Modified'/>
    <Value Type='DateTime' IncludeTimeValue='FALSE'>date value</Value>
    </Leq>
    </Where>
    </Query>
    </View>
    Above query returns zero items, it should return 3 items in my current scenario.
    If I do just the folllowing, three items are returned
    <View Scope='RecursiveAll'>
    <Query>
    </Query>
    </View>
    I need date filter to work with recursiveall . Not sure what is wrong with the query
    Student For Life

    Hi,
    Per my understanding, you might want to use “RecursiveAll” with date filter in your CAML query statement.
    I suggest you take the code demo below which writes in Server Object Model for a try in your environment to see if it can work for you:
    using (SPSite oSiteCollection = new SPSite("http://yoursite"))
    using (SPWeb web = oSiteCollection.RootWeb)
    SPList list = web.Lists["List1"];
    SPQuery qry = new SPQuery();
    qry.Query =
    @" <Where>
    <And>
    <Leq>
    <FieldRef Name='Modified' />
    <Value Type='DateTime'>2015-03-07T12:00:00Z</Value>
    </Leq>
    <Eq>
    <FieldRef Name='FSObjType' />
    <Value Type='Integer'>0</Value>
    </Eq>
    </And>
    </Where>";
    qry.ViewFields = @"<FieldRef Name='Title' />";
    qry.ViewAttributes = "Scope='RecursiveAll'";
    SPListItemCollection items = list.GetItems(qry);
    foreach (SPListItem item in items)
    Console.WriteLine(item["Title"]);
    Thanks
    Patrick Liang
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

Maybe you are looking for

  • Random wireless crashes ( need help urgently)

    Hi, I'm using a WRT54GSv4 router and I have two computer connected to it. One pc is connected by wire and the other computer ( IBM t60p labtop, integrated Intel Pro/wireless 3945abg, running MS Vista OS ) by wireless. the wired one is working flawles

  • Problem with Adobe Updater - WebPremium CS3

    Hello. Is anyone having trouble installing Adobe's latest updates to CS3 on Leopard (Macbook Pro)? It seems to hang on the Flash update. The update caused chaos on my Macbook Pro, constantly writing crash logs as soon as I quit a process another star

  • Unpacking and installing bootcamp on 24" imac (VIDEO)

    Just a little video on unpacking and installing XP on the new 24" Imac. Sorry you will have to copy and paste the links into your browser. Intelimac.org/vids/unpack.mov Intelimac.org/vids/bootcamp.mov

  • Use javascript to make a Flex panel?

    Trying to make a functional indeterminate progress bar, i'we tried almost anything i could think of. nothing worked (or it worked badly). the one thing i haven't tried yet is to use actionscript to create a palette with a swf movie inside. but i need

  • "My Computer" not showing ipod shuffle 2nd gen songs

    Im trying to take the music from my ipod shuffle, make a file, and transfer the music to that file to load onto itunes. My problem is that when I click on my ipod through "My Computer", it shows that it is empty. This is a pre-used computer that I ju