PnP PowerShell and Azure Automation – things to keep in mind

Just a post of things to keep in mind (for myself) when using PnP PowerShell and Azure Automation. I guess these are good things to keep in mind with PnP PowerShell in general.

PnP PowerShell is great for dealing with SharePoint and I use it a lot with Azure Automation Runbooks but it also gives a bunch of errors now and then. Figuring out how to solve them has taught me a few things to keep in mind for later.

1. When using cmdlets like Add-PnPListItem or Set-PnPListItem etc. it’s good to capture the output in a variable. That is to say, do something like $output = Add-PnPListItem -<whatever>. It looks like too much output from these cmdlets can mess up Runbooks, so best to capture them in a variable.

Thanks to this GitHub issue for pointing the way.

2. I typically do a Connect-PnPOnline at the beginning of the Runbook to connect to the site. And disconnect at the end. But I suppose it is a side effect of me having multiple Runbooks in the same Automation Account and Hybrid Runbook Workers, and them perhaps conflicting with each other, very often I get errors like ‘The current connection holds no SharePoint context. Please use one of the Connect-PnPOnline commands which uses the -Url argument to connect.’

It doesn’t matter if I add in a couple of try/ catch blocks to catch these and reconnect. I suspect this is because one of the Runbooks disconnects the connection, thus affecting the others.

The solution for this, it turns out, is to capture the connection in a variable and reuse that.

Now I can use that everywhere.

Since doing this, no more disconnects! Yay.

To eventually disconnect when quitting the Runbook don’t use Disconnect-PnPOnline any more. Simply null the variable: