I'm trying to display the versions of each item in a folder that contains sub folders.

Since I don't necessarily want to scan a whole SPO list, I specified to start in a certain folder, e.g. '/Documents/test'. If this starting folder contains a sub folder, e.g. '/Documents/test/subtest' I'm also able to retrieve it and its contents. However if this sub folder contains one more level my script doesn't retrieve it and its contents. I don't know what I can do to drill down recursively.

I appreciate any tips.

$site = "https://finnova-my.sharepoint.com/sites/contoso"  
$folderPath = "/Documents/test"

Connect-PnPOnline $site -Credentials $credential
$spoCred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials 
$credential.UserName, $credential.Password

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext $site
$ctx.Credentials = $spoCred

$web = $ctx.Web

$serverRelativeUrl = (Get-PnPList Documents).RootFolder.ServerRelativeUrl

$folder = $web.GetFolderByServerRelativeUrl($site+$folderPath)

ForEach ($subFolder in $folder.Folders)

  ForEach ($file in $subFolder.Files)
      $version = $file.Versions
      $versionCount = $version.Count
  • Put your code in one function and call it recursively. Obvious you need bit modification in you code. Jul 11, 2017 at 12:05

1 Answer 1


Have you tried programming recursively?

You could also make a list of folders to "work on"...

WHILE there are items in the WORKLIST
  take the first item off the work-list and call it WORKITEM
  FOREACH sub-items in WORKITEM
    IF sub-item is a ListItem 
      process the versions
    ELSE //it mus be a folder....
      append sub-item to WORKLIST

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.