Storing metaData of a file in SharePoint Library by breaking the hierarchy of folders

Copper Contributor

Hi there!

              I want to write a script that will take a document library from a SharePoint site fetches all its folders and subfolders as per their hierarchy create a new library on some other SharePoint site, creates its column, column should have the MetaData and choice values based on the source library folder names....  then move files from the source library to the destination and adopt the values of the columns based on the hierarchy of folders and subfolders in source library. have a script that will do this but just on single level depth but I need to do it for multilevel hierarchy. 

 

 

 

 

#Parameters
$SiteURL= "https://test.sharepoint.com/sites/......"
$ListName = "Migration"
$MetadataColumnName = "Project"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get All Items from the List
$List = Get-PnPList -Identity $ListName
$RootFolderURL = $List.RootFolder.ServerRelativeUrl
$ListItems = Get-PnPListItem -List $ListName -PageSize 500
$Files = $ListItems | Where {$_.FileSystemObjectType -eq "File"}
$Folders = $ListItems | Where {$_.FileSystemObjectType -eq "Folder" -and $_.FieldValues.FileDirRef -eq $RootFolderURL}
$FolderNames = @($Folders | ForEach-Object { $_.FieldValues.FileLeafRef})

#Get the column from list
$Field = Get-PnPField -Identity $MetadataColumnName -List $ListName -ErrorAction SilentlyContinue
If($Field -eq $Null)
{
#Create the Choice Metadata Column
Add-PnPField -List $ListName -DisplayName $MetadataColumnName -InternalName $MetadataColumnName -Type Choice -AddToDefaultView -Choices $FolderNames | Out-Null
}

#Loop through Each Folder and Update Metadata for Each File in the Folder
ForEach($Folder in $Folders)
{
#Get All Files from the Folder
$FolderFiles = $Files | Where {$_.FieldValues.FileDirRef -Eq $Folder.FieldValues.FileRef}
ForEach ($File in $FolderFiles)
{
#Get the File from List Item

#Move the File to Root Folder
Move-PnPFile -SourceUrl $File.FieldValues.FileRef -TargetUrl "$RootFolderURL/$($File.FieldValues.FileLeafRef)" -Force


Set-PnPListItem -List $ListName -Identity $File.Id -Values @{$MetadataColumnName = $Folder.FieldValues.FileLeafRef } | Out-Null
Write-host -f Yellow "Updated Metadata for File:"$File.FieldValues["FileRef"]


}


}

  

0 Replies