magritton
4/29/2020 - 6:09 PM

Upload Files Folders - SharePoint

This script iterates through a file structure and upload the files to a SharePoint Library preserving the directory format.

<# 
.SYNOPSIS 
    Uploads files and the file structure to a SharePoint library
 
.DESCRIPTION 
    This script iterates through a file structure and upload the files to a SharePoint Library
    preserving the directory format.

.NOTES 
┌─────────────────────────────────────────────────────────────────────────────────────────────┐ 
│ ORIGIN STORY                                                                                │ 
├─────────────────────────────────────────────────────────────────────────────────────────────┤ 
│   DATE        : 2020-04-29 
│   AUTHOR      : Mike Gritton 
│   DESCRIPTION : Initial Draft 
└─────────────────────────────────────────────────────────────────────────────────────────────┘ 
 
#>

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
     Add-PSSnapin Microsoft.SharePoint.PowerShell
}

#stop on error
$ErrorActionPreference = "Stop"

cls


Function UploadFiles($web,$path,$docLibraryName)
{
    $files = Get-ChildItem $path

    foreach ($file in $files) 
    {  
       if($file.GetType().Name -eq "DirectoryInfo")#test to see if the item is a folder/directory
       {
            #Item Is Folder

            Get-Member -InputObject $file
		    $newFolderName = $file.Name

            $docLibrary = $web.Lists[$docLibraryName]

		    $i = $docLibrary.Items.Add($docLibrary.RootFolder.ServerRelativeUrl,[Microsoft.SharePoint.SPFileSystemObjectType]"Folder", $file.Name);
		    $i.Update()

            UploadFiles $web $file.FullName ($docLibraryName + "/" + $newFolderName)
       }
       else
       {
            #Item is File

             #Open file
            $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
            $folder =  $web.GetFolder($docLibraryName)
        
            #Add file
            write-host "Copying file " $file.Name " to " $($folder.Url) "..."
            $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)

            #Close file stream
            $fileStream.Close();
       }

    }
}

$webUrl = "http://spdevserver"
$libraryDisplayName = "TestLibrary"
$localFolderPath = "C:\CodeFiles\TestFiles"

$web = Get-SPWeb $webUrl
UploadFiles $web $localFolderPath $libraryDisplayName

$web.Dispose()