PowerShell : Upload Document to Sharepoint Library - On prem

$sharePointSiteUrl = "https://mysites/sites/sitecollanem";
$sharePointLibraryName = "DocLibName";
$sourceFolder = "D:\FolderName";

Add-Type -Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'

Add-Type -Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'

#connect to the sharepoint library:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$web = Get-SPWeb $sharePointSiteUrl;

$documentLibrary = $web.Lists[$sharePointLibraryName];


$files = ([System.IO.DirectoryInfo] (Get-Item $sourceFolder)).GetFiles() | ForEach-Object { 


    #Create file stream object from file

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

    $contents = new-object byte[] $fileStream.Length

    $fileStream.Read($contints, 0, [int]$fileStream.Length);

    $fileStream.Close(); 

    write-host "Copying" $_.Name "to" $docLibrary.Title "in" $web.Title "..." 


    #Add file

    $folder = $documentLibrary.RootFolder

    $spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true)

    $spItem = $spFile.Item 

    

    Write-Host

    Write-Host -f Green "Added Document to Library !!!"

}

Write-Host

Write-Host All documents have been uploaded. 

Write-Host---------------------------------------------

Comments