I'm working with an account that has MFA set up and I'm trying to write a script to get me all the lists within a SharePoint Online site and its subsites.

The code works fine in the top-level site after providing MFA details, however, when I try to get the lists in the subsites the code returns the lists in the top-level site instead. This is because the connection\context I am passing is the connection for the top-level site.

I'm assuming I should be creating a new-PnP connection for each subsite but as there are a large number of subsites, I am trying to avoid re-authenticating using MFA for each subsite.

I have tried Get-PnPList with and without the -Web parameter but both times it says The current connection holds no SharePoint context. So, I am forced to use the -connection parameter and pass the $conn variable, which only holds the pre-existing context for the top-level site.

My code is as follows:

$conn = Connect-PnPOnline -ReturnConnection -Url https://test.sharepoint.com/sites/testsite

$rootLists = Get-PnPList -Connection $conn

$subWebs = Get-PnPSubWeb -Connection $conn

foreach($subweb in $subWebs)
    Get-PnPList -Web $subweb -Connection $conn #This is the bit that isn't behaving as I want.
  1. Is there a way to re-use the MFA credentials in the original connection and pass that to a new PnP connection request to avoid having to MFA for each subsite

  2. If 1 isn't possible. Is there a way to get the lists of a subsite without needing a new PnP connection and MFA request?

Thanks in advance.

1 Answer 1


According to my research and testing, if you want to connect to SharePoint with MFA, you can try to use the following code:

#Site Variables
$SiteURL = "https://crescent.sharepoint.com"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

If you want to get SharePoint Online subsite, please refer to the following code:

$SiteURL ="https://Crescent.sharepoint.com/sites/marketing/2018"
#Connect to PnP Online
Connect-PnPOnline -URL $SiteURL -Interactive
#Get the Web
$Web = Get-PnPWeb
#Get the title
Write-Host $Web.Title

More information for reference:

Connect to SharePoint Online using PowerShell with MFA (Multi-factor Authentication)

SharePoint Online: Get Subsites using PowerShell

Hope it can help you. Thanks for your understanding.

Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.