PnP PowerShell in Azure Automation tips

A few quick tips for running PnP PowerShell in Azure Automation in this article.

Firstly, you might run into AA runbooks constantly stopping suddenly and then restarting. They do this three times and then finally fail completely.
I've noticed this happens when you do not catch the return objects from PnP PowerShell commands in an object.
This issue on github shows that other people also experience this error. This seems to happen especially with the PnP actions Add-PnPListItem and Set-PnPListItem So you might have this in your runbook:
Set-PnPListItem -List $list -Identity $page.Id -Values @{$_.Name=$_.Value}; You're just running the command, and this will work (if you do it right :-)) when you run the PowerShell locally.
However, Azure Automation runbooks don't seem to like this way of programming. So instead, change it to this:
$setItem = Set-PnPListItem -List $list -Identity $page.Id -Values @{$_.Name=$_.Value} -ErrorAction SilentlyContinue -ErrorVariable errorSetListItem; Assigning the variable $setItem to the result of the PnP Command will stop the silent error from happening and the runbook will continue running correctly.

Notice the use of the ErrorAction and the ErrorVariable as well.
It's good practice to use these parameters in order to catch errors and then handle them appropriately. Especially when it's a script that you put in Azure Automation in order to run it regularly.

I used code like the following in my last assignment:

$setItem = Set-PnPListItem -List $list -Identity $page.Id -Values @{$.Name=$.Value} -ErrorAction SilentlyContinue -ErrorVariable errorSetListItem;

if ($errorSetListItem -and $errorSetListItem[0]){

Write-Output "Error setting list item field. Message: $($errorSetListItem[0])" | Tee-Object -file $aLogFileLocation -Append; } else

Write-Output "Succeeded in setting $($.Name) to $($.Value) on item $($page.Id) !!" | Tee-Object -file $aLogFileLocation -Append; }

The variable you use for ErrorVariable will contain the error message. If you check if there is an error, then you can log the error if there is one and otherwise log a success message. You can use the method Tee-Object to log to a file as well as show the message in the PowerShell window by the way.

Show Comments