Friday 9 June 2023

SharePoint Document Library Folder Metadata Extract using PNP PowerShell

I recently was asked to extract lots of metadata from one of our SharePoint solutions. The ask was the following:
  • Find all folders within a document library with a particular content type (folders are always at the root of the library.
  • For each folder, extract specific metadata fields (ergo get Folder metadata) including managed metadata fields.
  • Export the information to csv
The main reason I decided to post this was that I couldn't find a good example of extracting custom metadata fields from a Folder Content Type item.

This solution is based on PNP. It is fairly crude (no error handling) but does the job.

Aside, this script works with PnP.PowerShell version 1.9.0. My colleague tried it with an older version and it was unable to get the Managed Metadata Column labels.

#Folder content type name "My Folder Content Type"

#Get the following folder fields
#FolderFieldText1
#FolderFieldText2
#FolderFieldManagedMetadata1
#FolderFieldManagedMetadata2

#########################################
#Set following three variables before run
$siteUrl ="https://mytenant.sharepoint.com/sites/site 1/"  
$libraryName = "Documents"
$csvLocation = "C:\FolderMetadataExport.csv"
#########################################

#Add folder header
$folderHeader = "Path,Title,Folder Field Text1,Folder Field Text2,Folder Field Managed Metadata 1,Folder Field Managed Metadata 2,"
Add-Content -Path $csvLocation -Value $folderHeader

Connect-PnPOnline -url $siteUrl -UseWebLogin
$items = Get-PnPListItem -List $libraryName -Query "<View><ViewFields><FieldRef Name='FolderFieldText1'/><FieldRef Name='FolderFieldText2'/><FieldRef Name='FolderFieldManagedMetadata1'/><FieldRef Name='FolderFieldManagedMetadata2'/></ViewFields><Query><Where><Eq><FieldRef Name='ContentType'/><Value Type='Text'>My Folder Content Type</Value></Eq></Where></Query></View>"
foreach($item in $items){
    
    $folderInfo = '"'
    $folderInfo += $item.FieldValues.FileRef
    $folderInfo += '","'
    $folderInfo += $item.FieldValues["Title"]
    $folderInfo += '","'
    $folderInfo += $item.FieldValues["FolderFieldText1"]
    $folderInfo += '","'
    $folderInfo += $item.FieldValues["FolderFieldText2"]
    $folderInfo += '","'
    $folderInfo += $item.FieldValues["FolderFieldManagedMetadata1"].Label
    $folderInfo += '","'
    $folderInfo += $item.FieldValues["FolderFieldManagedMetadata2"].Label
    $folderInfo += '",'
    $folderInfo
    #Apend to csv
    Add-Content -Path $csvLocation -Value $folderInfo
}