Contents

Get files with specific names in SharePoint using PowerShell

 

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 a 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.

/images/powershell-screenshots/get-files-with-specific-names-img1.png
 

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

Get all the specific documents

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.

Then, 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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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

 

/images/powershell-screenshots/get-files-with-specific-names-img2.png
/images/powershell-screenshots/get-files-with-specific-names-img3.png
 

Thanks for reading!