Retrieve files with a specific name in a SharePoint Online site using PowerShell PnP

It’s not uncommon for companies to be wanting an inventory of files / folders in SharePoint.
But we can also narrow down the request, and look for only specific documents?

In this blog post, we’ll have a look at how to retrieve all the documents with particular name(s), from a Site. Maybe you have a naming convention for files / folders, and therefore, it’s easier to target.

 

Current documents in the site

As a proof (although technically, you can only take my word for it 🤫), I’ll run a script to check ALL the documents I have in my site…
In the image below, we can see that I have multiple documents, on different document libraries.

So our goal today, is to retrieve all the documents with the letters “ABC” or “BCD” in their name.

 

Retrieve all the specific docs

As usual, we’ll start by connecting to SharePoint Online using the Connect-PnPOnline cmdlet, we’ll store in a variable the path for our output file, and also store all the document libraries in another variable using the Get-PnPList.

#Connect to SPO
Connect-PnPOnline -Url https://<TENANT_NAME>.sharepoint.com/sites/BlogDemo  ### Change to your specific site ###

#Output path
$outputPath = "C:\users\$env:USERNAME\Desktop\specificFiles.csv"

#Store in variable all the document libraries in the site
$DocLibs = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101}

 

In our next steps, we will:

  • Store all the documents in $AllItems and expose a few fields
  • Create a IF statement –> if the file is like “ABC” or “BCD” (note the asterisks *ABC* for a wider search)
  • And finally, export the results to our .csv file

 

Full script below 🙂

#Connect to SPO
Connect-PnPOnline -Url https://<TENANT_NAME>.sharepoint.com/sites/BlogDemo  ### Change to your specific site ###

#Output path
$outputPath = "C:\users\$env:USERNAME\Desktop\specificFiles.csv"

#Store in variable all the document libraries in the site
$DocLibs = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101} 

#Loop thru each document library & folders
$results = @()
foreach ($DocLib in $DocLibs) {
    $AllItems = Get-PnPListItem -List $DocLib -Fields "FileRef", "File_x0020_Type", "FileLeafRef"
    
    #Loop through each item
    foreach ($Item in $AllItems) {
        if (($Item["FileLeafRef"] -like "*ABC*") -or ($Item["FileLeafRef"] -like "*BCD*")) {
            Write-Host "File found. Path:" $Item["FileRef"] -ForegroundColor Green
            
            #Creating new object to export in .csv file
            $results += New-Object PSObject -Property @{
                Path          = $Item["FileRef"]
                FileName      = $Item["FileLeafRef"]
                FileExtension = $Item["File_x0020_Type"]
            }
        }
    }
}
$results | Export-Csv -Path $outputPath -NoTypeInformation

 

 

 

There you go!

 

 

Leave a Reply

%d bloggers like this: