How to get items from a Sharepoint Online list using PowerShell?

Salah Elgo picture Salah Elgo · Sep 21, 2015 · Viewed 43.5k times · Source

I'm writing a PowerShell script that connects to a SharePoint website and I'm trying to get the items on a list. Here's my code:

$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

$SitePassword = ConvertTo-SecureString $SitePwd -AsPlainText -Force
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($SiteUser,$SitePassword)
$Context.Credentials = $Creds

$web = $Context.Web 
$Context.Load($web)
$Context.ExecuteQuery()

$List = $Context.Web.Lists.GetByTitle('Déposes')
$Context.Load($List)
$Context.ExecuteQuery()

But now I'm stuck with this $List Object and I can't find a way through. For now, I just want to display my list's items.

Answer

Vadim Gremyachev picture Vadim Gremyachev · Sep 22, 2015

The following example demonstrates how to retrieve list items using the SharePoint CSOM API in PowerShell:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")


Function Get-SPOContext([string]$Url,[string]$UserName,[string]$Password)
{
    $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
    return $context
}

Function Get-ListItems([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {
    $list = $Context.Web.Lists.GetByTitle($listTitle)
    $qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
    $items = $list.GetItems($qry)
    $Context.Load($items)
    $Context.ExecuteQuery()
    return $items 
}



$UserName = "[email protected]"
$Password = Read-Host -Prompt "Enter the password"    
$Url = "https://contoso.sharepoint.com/"


$context = Get-SPOContext -Url $Url -UserName $UserName -Password $Password
$items = Get-ListItems -Context $context -ListTitle "Tasks" 
foreach($item in $items)
{
   #...
}
$context.Dispose()