Cannot convert argument query with value Microsoft.SharePoint.Client.CamlQuery

When using PowerShell CSOM modules for SharePoint, I randomly stumbled into the error message: Cannot convert argument query with value Microsoft.SharePoint.Client.CamlQuery.

I was seeing the error when running a CAML query and calling GetItems() :

$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$query.ViewXml = "<View Scope='RecursiveAll'><Query></Query></View>"
$items = $sharepointList.GetItems($query)

It was strange because my scripts had worked for years with no problems! I immediately smelled a rat, and knew it had to be something to do with an assembly conflict.

I knew that the PowerShell CSOM SharePoint assemblies were called:

Microsoft.SharePoint.Client.dll

Microsoft.SharePoint.Client.Runtime.dll

So i ran the following in PowerShell to see which SharePoint assemblies were loaded in the current PowerShell session:

[System.AppDomain]::CurrentDomain.GetAssemblies() | Where FullName -like "*Microsoft.Sharepoint.Client*" | Select FullName, Location

And lo and behold, I found two versions of each assembly!

Newer Version 16.1.0.0 (C:\Program Files (x86)\WindowsPowerShell\Modules\PnP.PowerS
hell\1.12.0\Framework\):

Microsoft.SharePoint.Client.Runtime, Version=16.1.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c 
Microsoft.SharePoint.Client, Version=16.1.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c 

Older Version 16.0.0.0 (C:\Windows\Microsoft.NET\assembly\GAC_MSIL):

Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c 
Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c 

It appears that the older version was loading first, taking precedence over the newer version. So what was happening is that my call to GetItems() was using the older version and throwing the error! The solution was to simply remove the older version from my GAC and everything breathed into life again!

Maybe time to rebuild my development machine!?