Sunday 1 February 2015

Bulk Upload file from windows folder to SharePoint Document library using powershell

Steps to upload bulk or multiple files to SharePoint.

1. Create a New folder in local system to keep the multiple files to be uploaded to SharePoint. In my case it is C:\Documents.
2. Locate the SharePoint library that you want to upload the files to, 
  • Web URL  - In my case http://sitename:portnumber/
  • Document library URL - In my case "Documents"
  • Document library name  - In my case "Shared Documents"
3. Once the documents are uploaded to the library, the documents will be automatically deleted from the folder
4. Copy the below script to Windows Power shell ISI and Run
 
if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

#Script settings

$webUrl = "http://sitename:portnumber/"

$docLibraryName = "Shared Documents"          
$docLibraryUrlName = "Documents"


//** In C:\Documents as C:\Foldername**//
$localFolderPath = "C:\Documents" 

#Open web and library

$web = Get-SPWeb $webUrl

$docLibrary = $web.Lists[$docLibraryName]

$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

ForEach($file in $files)
{

    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

    #Add file
    $folder =  $web.getfolder($docLibraryUrlName)

    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    write-host "Success"

    #Close file stream
    $fileStream.Close();
}
#Delete all uploaded files from the folder

Get-ChildItem -Path $localFolderPath -Include *.* -File -Recurse | foreach { $_.Delete()}
#Dispose web

$web.Dispose() 
 
4. Once you complete copying, you will get Success message
5. Check your site, you will see all of the imported files in your SharePoint document library

No comments:

Post a Comment