Trying to upload files to subfolder in Sharepoint Online via Powershell

╄→尐↘猪︶ㄣ 提交于 2019-12-04 20:41:31

The error You cannot call a method on a null-valued expression. occurs since the $FolderToUpload object is not getting initialized at line:

$FolderToUpload = $FolderToBindTo | Where {$_.Name -eq $FolderName}

when $FolderName object points to sub folder name

The point is that $List.RootFolder.Folders returns only a folders located one level beneath under list or library, hence sub folder could not be referenced this way.

Instead you could consider the following options to reference a sub folder to add a file.

Using FileCreationInformation.Url property

Use FileCreationInformation.Url property to specify the folder url for a uploaded file.

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()


#Upload file(s)
Foreach ($File in (dir $Folder -File))
{
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
    $FileCreationInfo.URL = $List.RootFolder.ServerRelativeUrl + "/" + $FolderName + "/" + $File.Name
    $UploadFile = $List.RootFolder.Files.Add($FileCreationInfo)
    $Context.Load($UploadFile)
    $Context.ExecuteQuery()
}

Using Web.GetFolderByServerRelativeUrl method

Use Web.GetFolderByServerRelativeUrl method to retrieve a folder where file have to be uploaded:

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()

$TargetFolder = $Context.Web.GetFolderByServerRelativeUrl($List.RootFolder.ServerRelativeUrl + "/" + $FolderName);


#Upload file(s)
Foreach ($File in (dir $Folder -File))
{
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
    $FileCreationInfo.URL = $File.Name
    $UploadFile = $TargetFolder.Files.Add($FileCreationInfo)
    $Context.Load($UploadFile)
    $Context.ExecuteQuery()
}

You can also use the Office 365 Import service to bulk upload files to sharepoint online instead of using CSOM scripts.

This uses the new Sharepoint API which provides much faster speeds without any throttling as it uses scalable azure infrastructure.

https://support.office.com/en-us/article/Use-network-upload-to-import-SharePoint-data-to-Office-365-ed4a43b7-c4e3-45c8-94c8-998153407b8a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!