0

I'm wondering if someone can help. So I am trying to get a list of users from a SharePoint Online site using Powershell but get the following message.

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

My Code:

Add-PSSnapin Microsoft.SharePoint.PowerShell

Import-Module "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Import-Module "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$sourceUrl="https://site.sharepoint.com"
$UserName="user@domain"
$Password="********"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force

#$SPCredentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $UserName,$SecurePassword
#Connect-PnPOnline -Url $sourceUrl -Credentials $SPCredentials

$sourceCtx = New-Object Microsoft.SharePoint.Client.ClientContext($sourceUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$sourceCtx.Credentials = $credentials

$sourceWeb=$sourceCtx.Web  
$sourceCtx.Load($sourceWeb)   
$sourceUsers=$sourceWeb.SiteUsers
$sourceCtx.Load($sourceUsers)

#Iterate through source site users
foreach($user in $sourceUsers)
{
    Write-Host $user.Email
}

1 Answer 1

1

It seems you are missing following line after the sourceCtx.Load

sourceCtx.executeQuery()

1
  • Thanks but when I add sourceCtx.executeQuery() after the last sourceCtx.Load I get the following error. Exception calling "ExecuteQuery" with "0" argument(s): "The underlying connection was closed: An unexpected error occurred on a send."
    – JeffreyJ
    Apr 27, 2022 at 22:22

Your Answer

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

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