I'm trying to create an array of all subsites in our tenant. I'm able to get the first level of subsites but not the next level in a recursive manner.

Here's my code so far:

Connect-PnpOnline -Url XXX -Credentials XXX

$allSubwebs = @()

$currentSubwebs = Get-PnPSubwebs

foreach ($currentSubweb in $currentSubWebs) {
    $allSubwebs += $currentSubWeb.ServerRelativeUrl 

So this gives me the first layer of sub sites. But I know that some sub sites contain sub sites themselves. Of course I could nest foreach() loops but for this I would have to know in advance how many layers of subsites there are.

So my question is how I can do this recursively, i.e. drill down and populate the array.

Thanks for your help.

1 Answer 1


You need to use the Recurse parameter.

Modify your code as below:

$currentSubwebs = Get-PnPSubWebs -Recurse

Reference - Get-PnPSubwebs

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.