Thursday, December 10, 2015

SharePoint Online Powershell error Cannot find an overload for "Load" and the argument count: "1".

While using Powershell with CSOM you encounter the error "Cannot find an overload for "Load" and the argument count: "1"  when you do $context.Load while trying to access data from SharePoint online

Exact error:
Cannot find an overload for "Load" and the argument count: "1".
At C:\Users\XXX\Desktop\Scripts\Scripts.ps1:20 char:14
+ $Context.Load <<<< ($Lists)
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Resolution:

Make sure that you have installed the Sharepoint Client SDK - http://www.microsoft.com/en-us/download/details.aspx?id=35585

Since Load ClientRuntimeContext.Load<T> expects a generic ,in powershell you need to use the Invoke method to call generic methods.

Use the following method to load any objects instead of the Load method. Pass the current Context and the object that needs to be loaded.

Function Invoke-LoadMethod() {
param(
   $ctx,
   $clientObject
)
   $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
   $type = $clientObject.GetType()
   $genericMethodInvoker = $load.MakeGenericMethod($type)
   $genericMethodInvoker.Invoke($ctx,@($clientObject,$null))
}

Usage: Invoke-LoadMethod -ctx $ctx -clientObject $spWeb

Sample Code Execution:

Function Invoke-LoadMethod() {
param(
   $ctx,
   $clientObject
)
   $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
   $type = $clientObject.GetType()
   $genericMethodInvoker = $load.MakeGenericMethod($type)
   $genericMethodInvoker.Invoke($ctx,@($clientObject,$null))
}

#Specify tenant user and site col url
$user = "user@tenant.onmicrosoft.com"
$siteURL = "https://XX/sites/XXX"


#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"


$password = convertto-securestring "XXX" –asplaintext –force
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($user,$password)

#initialize context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($user,$password)
$ctx.Credentials = $creds

#Retrieve web related informations
$web = $ctx.Web
Invoke-LoadMethod -ctx $ctx -clientObject $web
$ctx.ExecuteQuery()

#Retrieve lists
$lists = $ctx.Web.Lists
Invoke-LoadMethod -ctx $ctx -clientObject $lists
$ctx.ExecuteQuery()

No comments:

Post a Comment