I've been attempting to upload files and folders to SharePoint Online using PowerShell. I'm almost there but there is something wrong with the code in the recursive method. It's upload the files into the folder below its supposed to. For example if I had a folder structure and each folder had 3 files:
Folder1\Folder2\Folder3
The files in Folder2 and Folder3 would upload to folder 3.
I know that the folders are getting uploaded first so the path of $UploadSubFolder is updated to the lower folder but I don't know how to fix it! Could you write a bit of code so that the files are uploaded first perhaps?
Can anyone help me with this problem ? Thanks!
Function ImportFiles()
{
ForEach($File in Get-ChildItem $CurrentFolder)
{
If($File.PSIsContainer -eq $false)
{
#Upload File to Folder in Sharepoint
$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
$Upload = $UploadSubFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
ElseIf($File.PSIsContainer -eq $True)
{
#Upload SubFolder
$CurrentFolder = $CurrentFolder + "\" + $File.Name
$NewFolder1 = Split-Path $File -leaf
$UploadSubFolder = $UploadSubFolder.Folders.Add($NewFolder1)
$Context.Load($UploadSubFolder)
$Context.ExecuteQuery()
ImportFiles
}
Else
{
Write-Host "Upload Complete"
}
}
}
#Get name of Root folder
$NewFolder = Split-Path $Folder -Leaf
#upload Root folder to sharepoint
$UploadFolder = $List.RootFolder.Folders.Add($NewFolder)
$Context.Load($UploadFolder)
$Context.ExecuteQuery()
ForEach($File in (dir $Folder))
{
if($File.PSIsContainer -eq $false)
{
#Upload File to Folder in Sharepoint
$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
$Upload = $UploadFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
else
{
$CurrentFolder = $Folder + "\" + $File.Name
#upload folder
$NewFolder = Split-Path $File -leaf
$UploadSubFolder = $UploadFolder.Folders.Add($NewFolder)
$Context.Load($UploadSubFolder)
$Context.ExecuteQuery()
ImportFiles
}
}