Grant-PnPAzureADAppSitePermission – Item not found

One of the things I commonly do is grant an Azure AD app registration permissions to a specific SharePoint site. I think I blogged about this in the past, but essentially it boils down to:

1) Granting the App Registration Sites.Selected permissions for Graph and ShaerPoint. You don’t need to do both, it depends on how you are accessing the site. If you app uses the Graph API then the former is needed; if your app uses the SharePoint API (e.g. PnP.PowerShell) then the latter is needed. I usually do both so the requestor can choose whichever method they want.

2) Running a bit of PowerShell to give the App Id permissions to this Site. Very generically, this is the bit of code I run:

This has always worked, until recently when I stumbled upon a site from a different geo. I did the usual, taking care to use the geo specific site Url (basically https://${tenantName}${region}) but it failed:

I tried changing the Admin Url too with a region specific one… but nope, no luck! We have many geos and none of them worked either.

The alternative is to use Graph API directly.

Thanks to the official docs for this.

Update: The above doesn’t always work. It keeps erroring: New-MgSitePermission_Create1: Item not found. Ditto with Invoke-MgGraphRequest.

In my testing I also found that even getting the permissions errors out:

What I finally stumbled upon is that if I were to get the lists in a site, then both getting and setting permissions works! So I do the following now:

Update (23 Jan 2023):

What I use currently, with a try/catch block to fail back as needed.