I am getting an Exception thrown when I try to run a script the first time after opening the PowerShell ISE but not the second time or anytime after that. It works everytime after the first run. I'm thinking it has something to do with the order I am calling things. Here is my code with some values replaced:
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$User = "[email protected]"
$pwFile = 'C:\encryptedPW.txt'
$PWord = (Get-Content $pwFile | ConvertTo-SecureString)
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Connect-MsolService -Credential $creds
Connect-AzureAD -Credential $creds
$SiteURL="https://example.sharepoint.com/sites/exampleSite/"
$listName="Example List"
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($creds.UserName, $creds.Password)
$list=$Ctx.Web.Lists.GetByTitle($listName)
$qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($qry)
$Ctx.Load($items)
$Ctx.ExecuteQuery()
It throws the exception on the "$Ctx.ExecuteQuery()" line with the exception: Exception calling "ExecuteQuery" with "0" argument(s): "Value cannot be null. Parameter name: password"