1

I would like to enumerate a Sharepoint Online list. The sample codes that I found are using the CSOM, which is fine, as the user who will run the script, won't have admin rights, but looks like I am missing something:

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

#set environment
$targetsite = "https://sites/testsite"
$targetlist = "testlist"

$adminUsername = "admin@account"
$secureAdminPassword = Read-Host -AsSecureString "please enter password"

#ask the user to log in
$usercredentials = Get-Credential
#creating sharepiont credentials object

#$sharepointcred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($usercredentials.UserName, $usercredentials.Password) 
$sharepointcred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($adminUsername, $secureAdminPassword) 
#tried both


#create context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($targetsite)
#assign sharepoint credentials to context
$Context.Credentials = $sharepointcred 
#read list
$list = Get-ListItems -Context $Context -ListTitle $targetlist

$items = Get-ListItems -Context $context -ListTitle $targetlist
foreach($item in $items)
{
   Write-Host $item.Title
}

I tried to get the credentials different ways (visible int the code), but none of them seems to be working, I get the following error message:

Credential: [ERROR] Exception calling "ExecuteQuery" with "0" argument(s): "Unable to connect to the remote server"

The account I'm using has site collection admin rights on the site and the link I am using is valid. Can someone give me a hint where does this code go wrong?

UPDATE: This looks like a connectivity issue, because the code works for me when I run it at home. So, looks like something in the company network is blocking the connection. Can someone please post what ports shall be opened and which URL's should be allowed to make this working, so I can ask our network guys to do what's necessary?

3
  • 2
    Have you looked into the PnP PowerShell? It will make your task so much easier. docs.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/… ,. By the way your code looks OK, you must have an issue with connectivity, your environment, or your variables. Feb 14, 2018 at 14:32
  • Yes, thank you, the code indeed works, this is a connectivity issue. Updated the question.
    – vilmarci
    Feb 14, 2018 at 16:27
  • Did you manage to find what ports are needed? I am having a similar issue as well
    – Krishant L
    Apr 20, 2018 at 18:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.