From a brilliant answer by @Evariste, I have prepared a
PowerShell code to migrate documents from file system to SPO Doc Lib with versions.
- The Document library must be enabled with Versioning
Consider following example, where I have a Document with 3 versions. Here we need to come up with a naming convention so that its easy for us to judge which is the latest one.
So its clear
Main_1.docx was the first version and
Main_4.docx is the latest
Note: In file system they have different names, but these must be
saved with similar name then and only then versions will be created.
Below is the PowerShell script I have used to create documents with its versions on SPO Document library.
#Specify tenant admin and site URL
$User = "email@example.com"
$SiteURL = "https://tenant.sharepoint.com"
$Folder = "D:\Version"
$DocLibName = "VersionCheck"
#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
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"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
$List = $Context.Web.Lists.GetByTitle($DocLibName)
Foreach ($File in (dir $Folder -File))
# Generate file's name.
$TempFileName = $File.BaseName.Split("_")
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
#$FileCreationInfo.URL = $File
# Here we replace different names by one single. i.e. in each iteration file name is Main_1, Main_2 etc.. $TempFileName will give us common name which is Main
$FileCreationInfo.URL = $TempFileName + $File.Extension
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)