Configure / Data / Provision

Add dummy folders and files to a SharePoint library

This sample shows how to add dummy folders and files into a SharePoint library, generating files within folders to perform testing.

Summary

This sample shows how to add dummy folders and files into a SharePoint document library. The script was used to generate files within folders to perform some testing.

Implementation

  1. Open Windows PowerShell ISE.
  2. Create a new file, e.g. TestDoc.docx and save it to a file server location, e.g. C:/Temp.
  3. A loop within another loop using While is used to create the number of specified files within each of the specified number of folders.
powershell
# Parameters
$SiteURL = "https://contoso.sharepoint.com/sites/Company311"

# Library in which to create the dummy files and folders
$LibraryName = "LargeLibrary"

# Location of the dummy file
$LocalFile= "C:\Temp\TestDoc.docx"

# Number of files to create within each folder
$MaxFilesCount = 20

# Number of folders to create in the libraru
$MaxFolderCount = 500

# The name of the folder to be created
$FolderName  = "Folder"

Try {
    # Get the File from file server
    $File = Get-ChildItem $LocalFile

    # Connect to SharePoint online site
    Connect-PnPOnline -Url $SiteURL -Interactive

    # Initialize folder counter
    $FolderCounter = 1
    
    While($FolderCounter -le $MaxFolderCount)
    {
        $newFolderName = $FolderName + "_" + $FolderCounter
        Try {
            # Add new folder in the library
            Add-PnPFolder -Name $newFolderName -Folder "$($LibraryName)" | Out-Null
            Write-Host -f Green "New Folder '$newFolderName' Created ($FolderCounter of $MaxFolderCount)!"   
            
            # Initialize file counter
            $FileCounter = 1

            While($FileCounter -le $MaxFilesCount)
            {
                $NewFileName = $File.BaseName + "_" + $FileCounter + ".docx"
                Try {
                    # Add new file in the folder
                    Add-PnPFile -Path $File -Folder "$($LibraryName)/$newFolderName" -NewFileName $NewFileName | Out-Null
                }
                Catch {
                    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
                }
                Write-Host -f Green "New File '$NewFileName' Created ($FileCounter of $MaxFilesCount)!"
                $FileCounter++
            }
        }
        Catch {
            Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
        }
        $FolderCounter++;
   }
}
Catch {
    Write-Host -f Red "Error Uploading File:"$_.Exception.Message
}

Contributors

Author(s)
Reshmee Auckloo
Ganesh Sanap
Adam Wójcik

Disclaimer

THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Tool documentation & references

Keep exploring