Search code examples
powershellsharepointcaml

Changes in SharePoint Powershell CAML Query Effect not Taken


In my CAML query for a SharePoint Power-shell script, the changes made in the CAML query is not taken effect.

May I know what am I doing wrong in my code snippet below?

cls
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set config variables
$baseUrl="http://test.com/"
$RDlistName ="RecordsDocument/Forms/TestReport"

#Get Web and List Objects
$web = Get-SPWeb $baseUrl
$RDlist = $web.Lists[$RDlistName]

#Define the CAML Query
$RDquery = New-Object Microsoft.SharePoint.SPQuery
$RDquery.Query = "@
<Where>
    <Eq>
        <FieldRef Name='ContentType' />
        <Value Type='Text'>Folder Content Type</Value> 
        #changes to above filter with an incorrect value still returns result *****
    </Eq>
</Where>"

#Get List Items matching the query
$RDitems = $RDlist.GetItems($RDquery)
$RDcount = 1

Write-host "Total Number of Folders in RecordsDocument:"$RDitems.count
Write-host ""

#Loop through Each Item
ForEach($RDitem in $RDitems)
{
    #Do something
    Write-host $RDcount"." $RDitem["Title"] "|" $RDitem["ContentType"]

    foreach($RDroleAssignment in $RDitem.RoleAssignments)  
    {
        Write-Host - $RDroleAssignment.Member.Name
    }
    $RDcount +=1
}

EDIT: In addition, the following error was observed..

You cannot call a method on a null-valued expression. At

D:\User\test.ps1:25 char:1

  • $RDitems = $RDlist.GetItems($RDquery)

  • + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    

Solution

  • My test script(hope it helps):

    if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
        Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    }
    
    #Set config variables
    $baseUrl="http://site/"
    $RDlistName ="MyDoc"
    
    #Get Web and List Objects
    $web = Get-SPWeb $baseUrl
    $RDlist = $web.Lists[$RDlistName]
    
    #Define the CAML Query
    $RDquery = New-Object Microsoft.SharePoint.SPQuery
    $RDquery.Query = "@
    <Where>
        <Eq>
            <FieldRef Name='ContentType' />
            <Value Type='Computed'>Folder</Value>        
        </Eq>
    </Where>"
    
    #Get List Items matching the query
    $RDitems = $RDlist.GetItems($RDquery)
    $RDcount = 1
    
    Write-host "Total Number of Folders in RecordsDocument:"$RDitems.count
    Write-host ""
    
    #Loop through Each Item
    ForEach($RDitem in $RDitems)
    {
        #Do something
        Write-host $RDcount"." $RDitem["Title"] "|" $RDitem["ContentType"]
    
        foreach($RDroleAssignment in $RDitem.RoleAssignments)  
        {
            Write-Host - $RDroleAssignment.Member.Name
        }
        $RDcount +=1
    }
    

    enter image description here