Stupid error: ‘@’ is an unexpected token. The expected token is ‘;’. Line 16, position 57.

I have this Runbook that queries and updates a SharePoint Online list, checks various AD forests, etc. and for the past 3 days it was giving the following error:

For a while I thought this was coming from AD and spent all my effort troubleshooting that. And while I didn’t find anything to that end, when Googling the error I found one KB article that gave the impression it was AD related and that enforced my opinion. Turns out I was wrong.

Most other Google results were to do with XML, but I wasn’t using any XML in my code. I found one result that pointed to the PnP cmdlets but that was to do with the Connect-PnPOnline cmdlet and I didn’t have any issues there either.

Anyways, after a lot of head-wrangling I finally found the issue. One of the entries I was processing had an ampersand in the email address (like say abc&def@mydomain.com). And while AD had no issue with it, nor did the Add-PnPListItem cmdlet that added this to SharePoint Online, when I was searching for this entry it was failing.

I was searching like this:

And this part was failing. So what I did is escape the ampersand in the email address (thanks to) by modifying the code like this:

And now it works!