M365 Dev Blog

Find SharePoint documents by file extension

file extension

This blog post contains a simple PowerShell script that you can use to find all SharePoint files from a certain file extension. It creates a CSV file with the results, so you can easily consume or manipulate that information. 

On my previous blog post, I shared a script to find documents by file type using search. You can read more here. This approach works well for file types that are indexed by search, but this is not always the case. 

This script addresses that limitation as it parses all files across all document libraries. It checks if the file name ends with the extension specified and adds the item to a CSV file if so.

# Variables
$siteUrl = "https://XXXXXXXX.sharepoint.com/sites/XXXX"
$FileType = "lnk"

$LogFile = "C:\users\$env:USERNAME\Desktop\File Type - $FileType.csv"

#Connect to SPO
Connect-PnPOnline -Url $siteUrl -UseWebLogin

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

$results = @()
foreach ($DocLib in $DocLibrary) {

    #Get list of all items in the document library
    $AllItems = Get-PnPListItem -PageSize 1000 -List $DocLib -Fields "ID"
    
    #Loop through each files/folders in the document library for folder size = 0
    foreach ($Item in $AllItems) {
        if ($Item["FileLeafRef"] -like "*.$FileType") {

            Write-Host "Item:" $Item["FileRef"] -ForegroundColor Yellow
                
            #Creating object to export in .csv file
            $results += [pscustomobject][ordered] @{
                ID       = $Item["ID"] 
                FileName = $Item["FileLeafRef"] 
                FilePath = $Item["FileRef"]
            }
            
        }#end of IF statement
    }
}
$results | Export-Csv -Path $LogFile -NoTypeInformation
Exit mobile version