SharePoint 2010 – How to add files in a folder to a SharePoint library with PowerShell

Written by Wouter Baltus   // 14 March 2012   // 1 Comment

How to add files in a folder to a SharePoint library with PowerShell?
Use this script!


$siteurl = "http://sharepoint.com"
$spWeb = Get-SPWeb $siteurl
$docLibraryName = "LibraryName"
$localFolderPath = "D:\Upload"
$docLibrary = $spWeb.Lists[$docLibraryName] 

$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles() | ForEach-Object {
    $fileStream = ([System.IO.FileInfo] (Get-Item $_.FullName)).OpenRead()
    $contents = new-object byte[] $fileStream.Length
    $fileStream.Read($contents, 0, [int]$fileStream.Length);
    $fileStream.Close();
    write-host "Copying" $_.Name "to" $docLibrary.Title "in" $spWeb.Title "..."
    $folder = $docLibrary.RootFolder
    $spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true)
    $spItem = $spFile.Item 

}


Similar posts

1 COMMENT

  1. By abdul raoof k, 30 July 2012

    I have a similar requirement which needs the user profile photo to be upladed programmatically and i am following the below link.
    (http://get-spscripts.com/2010/12/upload-multiple-user-profile.html?showComment=1343631879879#c2583649327795206294)
    But I am getting an error at this step
    $spFile = $spPhotosFolder.Files.Add($spFullPath, $_.OpenRead(), $true)

    It is throwing the following error
    Copying domain_abdul.JPG to User Photos in …
    The script has stopped because there has been an error: Exception calling “Add” with “3″ argument(s): “The system cannot find the file specified.
    (Exception from HRESULT: 0×80070002)”

    Your help will be greatful as i am stuck with this requirement

    Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *