SharePoint Upload Document to Library Using PowerShell

This PowerShell script is used to upload all document from a folder to a SharePoint Site. You should remember one thing that this PowerShell script and your document folder must be saved on same location.

cls 
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue 
Add-PSSnapin Microsoft.SharePoint.Powershell


$webUrl = "http://sp2010/"
$docLibraryName = "My Library"
$localFolderPath = "Files"

#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 = $docLibrary.RootFolder
    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();
}
#Dispose web
$web.Dispose()

Comments

  1. How could this be modified to say every file in the folder including sub folders?

    ReplyDelete
    Replies
    1. You can modify $localFolderPath. for example "C:\Users\Administrator\Desktop\NewFolder\SubFolder"

      Delete

Post a Comment

Popular posts from this blog

C# Copy files from one server to another

Suppress StyleCop SA1600

Telerik Rad Grid Sorting