Skip to content
May 17, 2025
  • Administration
  • PowerShell
  • SharePoint 2013
  • SharePoint 2019

Get-SPNote

All about SharePoint and PowerShell

  • Home
  • SharePoint 2013
  • Extract Documents to Folder based on Managed Metadata Column – SharePoint
  • Administration
  • PowerShell
  • SharePoint 2013
  • SharePoint 2019

Extract Documents to Folder based on Managed Metadata Column – SharePoint

SPNoteAdmin4 years ago2 years ago06 mins

How to Extract documents from Multiple Document libraries in to Folders. Each has a Managed Metadata Column with Sub Terms.

I have created three Functions to

  • Download Document
  • Create Folder
  • Main Method

Addition to above, script will log the Document URL and destination Folder Path in .log file

Create Folder

 Function Create-Folder
{
    param ($folderPath)
 
    if (!(Test-Path -path $folderPath))
    {
        New-Item $folderPath -type directory
    }
}

Download Document

This was stolen from  (  Stackoverflow 😁 )

Function Download-Document
{
    param($web, $folderPath, $docItem) 
    #File Download Snippet Reffered From : https://stackoverflow.com/questions/43350575/how-to-use-powershell-to-download-files-from-sharepoint
      $File = $web.GetFile($docItem.Url)
        $Binary = $File.OpenBinary()
        $detinationPath = $folderPath + "\" + $File.Name;
        $Stream = New-Object System.IO.FileStream($detinationPath), Create
        $Writer = New-Object System.IO.BinaryWriter($Stream)
        $Writer.write($Binary)
        $Writer.Close() 
        Add-Content -Path $logFilePath -Value "$($docItem.ParentList.Title)|$($docItem.Url)|$($File.Name)|$($detinationPath)";
 
}

Folder Structure was like below (I have created two top level folders to keep the term related documents

$RootFolder ="Vehicles"

$SecondFolder="Brands"

$SecondFolderLibraryName="Volvo_Library" #Library Name (Title)

$ChildFolderColumnName="VehicleTypeColum" #Metadata Column Name

Main Method

Function Extract-DocLibrary
{
    TRY
    {
        #Check for Root Folder
        $rootFolderpath = $dataFolderPath+$RootFolder;
        Create-Folder -folderPath $rootFolderpath ;
 
        #check and Create Second Folder (Folder for Library)
        $secondFolderPath = $dataFolderPath+$RootFolder+"\"+$SecondFolder;
        Create-Folder -folderPath $secondFolderPath;
 
        $spWeb = Get-SPWeb -Identity $siteURL;
        $DocLibrary = $spWeb.Lists[$SecondFolderLibraryName]
 
        IF($DocLibrary)
        {
            $allDocs = $DocLibrary.Items;
 
            foreach ($document in $allDocs)
            {
               $metadataField =  $document[$ChildFolderColumnName]
               if(![string]::IsNullOrEmpty($metadataField))          
               {
                     Write-Host $metadataField.Label;
                    $FirstLevleLable= $metadataField.Label;
                    IF($FirstLevleLable.Contains(':'))
                    {
                        $isFirstLevel= $true;
                        #in this section I'm splitting the Sub Terms by ":"
                        $terms = $FirstLevleLable -split ':';
 
                        foreach ($term in $terms)
                        {
                            #creating Sub Folder Structure
                            IF($isFirstLevel)
                            {
 
                            $thirdLevelFolder = $secondFolderPath+"\"+$term;
                            $isFirstLevel =$false;
                            Write-Host "  "$thirdLevelFolder -f Green;
                                Create-Folder -folderPath $thirdLevelFolder;
                            }
                            else
                            {
                                $thirdLevelFolder=$thirdLevelFolder+"\"+$term;
                                Write-Host "   "$thirdLevelFolder -f Cyan;
                                Create-Folder -folderPath $thirdLevelFolder;
                            }
                        }
                    }
                    Else
                    {
                        $thirdLevelFolder = $secondFolderPath+"\"+$FirstLevleLable;
                        Write-Host $thirdLevelFolder -f Yellow
                        Create-Folder -folderPath $thirdLevelFolder;
                        #Download-Document -web $spWeb -folderPath $thirdLevelFolder -docItem $document;
                    }
 
                   Download-Document -web $spWeb -folderPath $thirdLevelFolder -docItem $document;
               }
               Else
               {
                    #No Metadata Tag Updated for this Document
                     Write-Host $secondFolderPath;
                     Download-Document -web $spWeb -folderPath $secondFolderPath -docItem $document;
               }
            }
        }
    }
    Catch
    {
    }
    Finally
    {
        $spWeb.Dispose()
    }
}
 
 
Extract-DocLibrary;

Find Entire Script from Below Section


Add-PSSnapin "Microsoft.SharePoint.PowerShell"
 
$timeStamp = Get-Date;
$ExecutionIDTitle =$timeStamp.ToString("yyyy-MM-dd-HH-mm");
$ExecutionID =$timeStamp.ToString("yyyyMMddHHmm");
 
 
$siteURL ="SiteURL";
$dataFolderPath = "FolderPath\Data\";
$logFilePath = "FolderPath\Log\$ExecutionID-Extraction.log"; 
 
Add-Content -Path $logFilePath -Value "SPLibraryName|SPDocURL|FileName|FolderPath"
 
 
 
$RootFolder ="Vehicles"
$SecondFolder="Brands"
$SecondFolderLibraryName="Volvo_Library" #Library Name (Title)
$ChildFolderColumnName="VehicleTypeColum" #Metadata Column Name
 
 
Function Download-Document
{
    param($web, $folderPath, $docItem) 
 
    #File Download Snippet Reffered From : https://stackoverflow.com/questions/43350575/how-to-use-powershell-to-download-files-from-sharepoint
      $File = $web.GetFile($docItem.Url)
        $Binary = $File.OpenBinary()
        $detinationPath = $folderPath + "\" + $File.Name;
        $Stream = New-Object System.IO.FileStream($detinationPath), Create
        $Writer = New-Object System.IO.BinaryWriter($Stream)
        $Writer.write($Binary)
        $Writer.Close()
 
        Add-Content -Path $logFilePath -Value "$($docItem.ParentList.Title)|$($docItem.Url)|$($File.Name)|$($detinationPath)";
 
}
 
 Function Create-Folder
{
    param ($folderPath)
 
    if (!(Test-Path -path $folderPath))
    {
        New-Item $folderPath -type directory
    }
}
 
Function Extract-DocLibrary
{
    TRY
    {
        #Check for Root Folder
        $rootFolderpath = $dataFolderPath+$RootFolder;
        Create-Folder -folderPath $rootFolderpath ;
 
        #check and Create Second Folder (Folder for Library)
        $secondFolderPath = $dataFolderPath+$RootFolder+"\"+$SecondFolder;
        Create-Folder -folderPath $secondFolderPath;
 
        $spWeb = Get-SPWeb -Identity $siteURL;
        $DocLibrary = $spWeb.Lists[$SecondFolderLibraryName]
 
        IF($DocLibrary)
        {
            $allDocs = $DocLibrary.Items;
 
            foreach ($document in $allDocs)
            {
               $metadataField =  $document[$ChildFolderColumnName]
               if(![string]::IsNullOrEmpty($metadataField))          
               {
                     Write-Host $metadataField.Label;
                    $FirstLevleLable= $metadataField.Label;
                    IF($FirstLevleLable.Contains(':'))
                    {
                        $isFirstLevel= $true;
                        #in this section I'm splitting the Sub Terms by ":"
                        $terms = $FirstLevleLable -split ':';
 
                        foreach ($term in $terms)
                        {
                            #creating Sub Folder Structure
                            IF($isFirstLevel)
                            {
 
                            $thirdLevelFolder = $secondFolderPath+"\"+$term;
                            $isFirstLevel =$false;
                            Write-Host "  "$thirdLevelFolder -f Green;
                                Create-Folder -folderPath $thirdLevelFolder;
                            }
                            else
                            {
                                $thirdLevelFolder=$thirdLevelFolder+"\"+$term;
                                Write-Host "   "$thirdLevelFolder -f Cyan;
                                Create-Folder -folderPath $thirdLevelFolder;
                            }
                        }
                    }
                    Else
                    {
                        $thirdLevelFolder = $secondFolderPath+"\"+$FirstLevleLable;
                        Write-Host $thirdLevelFolder -f Yellow
                        Create-Folder -folderPath $thirdLevelFolder;
                        #Download-Document -web $spWeb -folderPath $thirdLevelFolder -docItem $document;
                    }
 
                   Download-Document -web $spWeb -folderPath $thirdLevelFolder -docItem $document;
               }
               Else
               {
                    #No Metadata Tag Updated for this Document
                     Write-Host $secondFolderPath;
                     Download-Document -web $spWeb -folderPath $secondFolderPath -docItem $document;
               }
            }
        }
    }
    Catch
    {
    }
    Finally
    {
        $spWeb.Dispose()
    }
}
 
 
Extract-DocLibrary;

Watch Video for more details

Tagged: Managed Metadata PowerShell SharePoint Management Shell SharePoint On-Prem

Post navigation

Previous: How To Fix Nintex Workflow Activation Error
Next: Free SharePoint Pre-Upgrade Check List

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Free SharePoint Pre-Upgrade Check List

SPNoteAdmin2 years ago2 years ago 0

How To Fix Nintex Workflow Activation Error

SPNoteAdmin5 years ago2 years ago 0

Enabling Nintex Workflow Feature Failed – Sorry, Something Went Wrong

SPNoteAdmin5 years ago2 years ago 0

Recent Posts

  • Free SharePoint Pre-Upgrade Check List
  • Extract Documents to Folder based on Managed Metadata Column – SharePoint
  • How To Fix Nintex Workflow Activation Error
  • Enabling Nintex Workflow Feature Failed – Sorry, Something Went Wrong
  • System.Data.SqlClient.SqlException (0x80131904): The EXECUTE permission – User Profile Issue

Get Free SharePoint Pre-Upgrade Check List

Set yourself up for a successful upgrade by following in the footsteps of those who have already done it right.

Access Denied Administration Administrator Best Practice Delete e-book free books free resources Get-AppPoolDetails Get-AuthProviders Get-ExecutionPolicy Get-OutgoingMail Get-SPFarmDetails Large Lists list view threshold Managed Metadata Microsoft NetBios Nintex Nintex Form Nintex Workflow PDF Icon Permission Issue PowerShell Pre-Upgrade Publish Form Search Set-ExecutionPolicy SharePoint SharePoint 2013 SharePoint document Icon SharePoint Management Shell SharePoint On-Prem SharePoint Upgrade Site Collection SPQuery Sub sites SubSites Super Reader Super User Upgrade User Profile Service Web Application Workflow WSS_Content_Application_Pools

Recent Comments

No comments to show.
Trendy News - News WordPress Theme. All Rights Reserved 2025. Powered By BlazeThemes.