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 "")
{
    Write-Host
    $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 "")
{
    Write-Host
    $localPath = Read-Host -Prompt " – Please enter the full path to the local directory that contains the documents to be uploaded"
}
Write-Host

## 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…."
    $OpenList.Delete()
    $OpenWeb.Update()
}

## 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
$NewList.Update()
$OpenWeb.Update()

## Tidy up
$OpenWeb.Dispose()

## 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
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: