Easily Retrieve SharePoint attachment names with PnP PowerShell

Have you ever noticed that in SharePoint, when you attach files in a _list item_, you can add the column Attachments and visualize a little clip thing, but it doesn’t show the number of files nor their names? So what if you wanted to know about all the attachments in a list item? In multiple lists? Are you going to… click click click?

Noooo, let’s use PnP PowerShell for that! 🤠

What do we have to start with?

I currently have 2 lists (List123 & List456), with 2x list item each (one for each of them doesn’t have any attachment)

This is what’s happening:

  • Connect to SPO using Connect-PnPOnline
  • Create variables for exporting the results + narrowing down the lists to only Lists and not libraries (full template codes)
  • Loop through each list
  • Loop through each list item
  • Loop through each property of the item(s)

We’re using the Get-PnPProperty cmdlet to expand our search for the correct properties.

So here we go:

#Connect to SPO
Connect-PnPOnline -Url https://<TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>

#Variables
$results = @()
$allLists = Get-PnPList | Where-Object {$_.BaseTemplate -eq 100}

#Loop thru each lists
foreach($list in $allLists){
    $allItems = Get-PnPListItem -List $list.Title
    
    #Loop thru thru each item in the list(s)
    foreach ($item in $allItems){
        $allProps = Get-PnPProperty -ClientObject $item -Property "AttachmentFiles"
        
        #Loop thru each property and grab the ones we want!
        foreach($prop in $allProps){
            $results += [pscustomobject][ordered]@{
                ListName = $list.Title
                ItemName = $item["Title"]
                ItemCreatedBy = $item.FieldValues.Author.LookupValue
                ItemLastModifiedBy = $item.FieldValues.Editor.LookupValue
                AttachmentNames = $prop.FileName
                ServerRelativeUrl = $prop.ServerRelativeUrl
            }
        }
    }
}
$results | Export-Csv -Path "<YOU_PATH>" -NoTypeInformation

The results

Without exporting the results, it would look like this:

Exporting in a .csv file, it would look like that:

We can see that in the list called List123, we’ve got 2x attachments in item “test1“, and 3x under the “HelloWorld” item in the list called List456.

Thanks for reading! 🙂

Discover more from Veronique's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading