PnP PowerShell and more...

Here I occasionally post about Microsoft 365 Patterns and Practices in general and PnP PowerShell more specifically.

Automatic Context Switching in PnP PowerShell

2018-03-21 2 min read PowerShell SharePoint

PnP PowerShell does something we call ‘context switching’. Let me show you how this is making your life a tiny bit easier:

Connect-PnPOnline https://contoso.sharepoint.com
Get-PnPList
Get-PnPTenantSite

This will connect first to your root site collection in your tenant, return all the lists in the site, and then the next cmdlet will show you all the (classic) site collections in your tenant. Normally you would have to connect (if you’re a developer, you have to create a new ClientContext) to your tenant admin site first in order to do this. However, already for quite some time we made the cmdlets a bit more ‘intelligent’.

The tenant admin cmdlets are ‘aware’ of the fact that they need to connect to a tenant admin site. The moment you execute them and you are not connected to that site, it will switch its context (it will ‘clone’ the context, reusing the current credentials) to your tenant admin site, do the work, and restore the original context.

That makes it very transparent for you to use them, and you don’t have to reconnect in your scripts either.

Notice that we make a simple assumption of what the tenant admin site URL is. We basically take the hostname, and append -admin to it. In some cases (SPO-D) this will not work, and you will have connect to the tenant admin site anway with Connect-PnPOnline.