I am trying to write a script using Power Shell to copy an entire Directory (Main Folders, Sub-Folders, and all Files in between) on a Network Share to SharePoint online. The most I have accomplished is creating the first layer. The Directory folder is uploaded just fine to my documents library on SharePoint. Next, I have been able to create the first layer consisting of the Main Folders and all files under the Directory Folder. However, I have not been able to upload any of the sub-folders or files that correspond with the Main Folders. Any assistance will be greatly appreciated. The code I am working with is below:
#Upload file
Function ImportFiles()
{
#Get name of directory
$NewDirectory = Split-Path $Directory -Leaf
#upload directory to sharepoint
$UploadNewDirectory = $List.RootFolder.Folders.Add($NewDirectory)
$Context.Load($UploadNewDirectory)
$Context.ExecuteQuery()
$FoldersInDirectory = Get-ChildItem $Directory
#upload full directory contents to sharepoint
Foreach ($Item in $FoldersInDirectory)
{
if($Item | ? {$_.PsIsContainer -eq $true})
{
$Folder = $Item
$UploadFoldersInDirectory = $UploadNewDirectory.Folders.Add($Folder)
$Context.Load($UploadFoldersInDirectory)
$Context.ExecuteQuery()
$SubFoldersInFolder = Get-ChildItem $FoldersInDirectory
Foreach ($SubItem in $SubFoldersInFolder)
{
if($SubItem | ? {$_.PsIsContainer -eq $true})
{
$SubFolder = $SubItem
$UploadSubFoldersInDirectory = $UploadFoldersInDirectory.Folders.Add($SubFolder)
$Context.Load($UploadSubFoldersInDirectory)
$Context.ExecuteQuery()
}
}
}
elseif($Item | ? {$_.PsIsContainer -eq $false})
{
$File = $Item
$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 = $UploadNewDirectory.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
}
} # end function ImportFiles ImportFiles