Migrating files from our local file system to one of the Document Library in SharePoint Site can be achieved easily using CSOM PowerShell
.
First get the client namespaces installed on your machine
Get SharePoint 2013 Client Components and install on your machine from where you wish to execute the script.
Once you finish installing the client components, all the client namespaces will be located at below location.
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\
Add references of client namespaces in your PowerShell script
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 SharePoint Site.
# SharePoint URL
#
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext("http://YourSite")
$web = $ctx.Web
# Authenticating
#
$cred = Get-Credential
$ctx.Credentials = $cred
# Get Document Library
#
$DocLib = $web.Lists.GetByTitle("NameOfYourDocLib")
# Load the object
#
$ctx.Load($web)
$ctx.Load($DocLib)
$ctx.ExecuteQuery()
Get your files from the file system into an object.
# Get all files
#
$Files = Get-ChildItem -Path "c:\TestFolder" | ? {$_.psIsContainer -eq $False}
Read each file and upload it onto a Document Library.
# Upload all files in the root folder of the document library
#
Foreach ($File in $Files) {
Write-Host "Uploading file.." -ForegroundColor Green
$FileFullName = $File.FullName
$FileStream = New-Object IO.FileStream($FileFullName, [System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File.Name
$FileUpload = $DocLib.RootFolder.Files.Add($FileCreationInfo)
$ctx.Load($FileUpload)
$ctx.ExecuteQuery()
}