2

I am trying to delete items in a list using CSOM powershell but it doesn't seem to work at all, Here is my code atm which is trying to print out the title of my list items but this isn't working either(not printing out any data). Where am I going wrong?

$web = $ctx.Web
$site = $ctx.Site     
$ctx.Load($web)     
$list = $web.Lists.GetByTitle("Pages")
write-host $list.ItemCount        
Write-Host ("Deleting old result page")
Write-Output("Deleting old result page")
foreach($listItem in $list)
{        
    $ctx.Load($listItem)    
    $ctx.ExecuteQuery()    
}
5

Its because you haven't loaded the $list.

Use below code and try

$web = $clientContext.Web
$list = $web.Lists.GetByTitle("Pages")
$clientContext.Load($list)
$clientContext.ExecuteQuery()
$count = $list.ItemCount
$newline = [environment]::newline
Write-Host -NoNewline "Deleting listitems from Pages" -foregroundcolor black -backgroundcolor yellow
$continue = $true
while($continue)
{
    Write-Host -NoNewline "." -foregroundcolor black -backgroundcolor yellow
    $query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(100, "ID")
    $listItems = $list.GetItems( $query )
    $clientContext.Load($listItems)
    $clientContext.ExecuteQuery()       
    if ($listItems.Count -gt 0)
    {
        for ($i = $listItems.Count-1; $i -ge 0; $i--)
        {
            $listItems[$i].DeleteObject()
        } 
        $clientContext.ExecuteQuery()
    }
    else
    {
        Write-Host "." -foregroundcolor black -backgroundcolor yellow
        $continue = $false;
    }
}
Write-Host "All listitems deleted from Pages." -foregroundcolor black -backgroundcolor green

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.