Upload Multiple Documents to SharePoint Library

Here’s my script to upload all the documents found in a particular file system folder to a SharePoint document library. You can specify the destination URL and local directory path as parameters to the script or simple enter them at runtime.

WARN16 WARNING: This script first deletes the library if it already exists – please remove this step if this is not what you want. It’s there in my script so I can rebuild my environment rapidly after ever demo…

param ([String]$spPath, [String]$localPath)

## Load the SharePoint Snapin so the script can be executed from PowerShell editor
Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

# get the SharePoint path if not specified
if ($spPath -eq "")
    $spPath = Read-Host -Prompt " – Please enter the fully qualified url to the destination document library"
# get the local path if not specified
if ($localPath -eq "")
    $localPath = Read-Host -Prompt " – Please enter the full path to the local directory that contains the documents to be uploaded"

## Define our library name and web url
$LibraryName = $spPath.Substring($spPath.LastIndexOf("/")+1)
$webUrl = $spPath.Substring(0,$spPath.LastIndexOf("/"))

## Define a function to return the destination file name
Function BuildFileName($filename)
    "$webUrl/$LibraryName/" + $(split-path -leaf $filename)

## Delete our library – by name
$OpenWeb = Get-SPWeb $webUrl
$OpenList = $OpenWeb.Lists[$LibraryName]
if ($OpenList -ne $null)
    Write-Host "Deleting $LibraryName Library…."

## Create our library
Write-Host "Creating new $LibraryName Library…."
$OpenWeb.Lists.Add($LibraryName, "A SharePoint document library created via PowerShell", 101) | Out-Null
$NewList = $OpenWeb.Lists[$LibraryName]
$NewList.OnQuickLaunch = 1

## Tidy up

## Upload all the documents found in the specified location
Write-Host "Uploading all documents from $sourceDocs"
$webClient = New-Object System.Net.WebClient
$webClient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
dir $localPath | % {
    Write-Host "Uploading: $_" -nonewline
    $fName = BuildFileName $_
    $webClient.UploadFile($fName,"PUT", $_.FullName)
    Write-Host " done" -ForegroundColor Green