使用Powershell上传到SharepointOnline子文件夹

时间:2017-03-08 23:45:42

标签: powershell sharepoint sharepoint-online

好像我可以将文件上传到SPO的网站集URL而不是子文件夹。例如,我可以上传到“https://xyz.sharepoint.com/sites/Reporting”,但不能上传到“https://xyz.sharepoint.com/sites/Reporting/Sales”。这是工作代码的相关位:

$Username = "me@domain.com"
$Password = "Password"
$SiteCollectionUrl = "https://xyz.sharepoint.com/sites/Reporting"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$DocLibName = "Sales"

$Folder="C:\MySalesFolder"

    Function Get-SPOCredentials([string]$UserName,[string]$Password)
    {
       $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
       return New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
    }
     $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl)
     $Context.Credentials = Get-SPOCredentials -UserName $UserName -Password $Password

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

    #Upload file
    Foreach ($File in (dir $Folder -File))
    {
    $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 = $List.RootFolder.Files.Add($FileCreationInfo)
    $Context.Load($Upload)
    $Context.ExecuteQuery() 

我试图硬编码“/ Sales”子文件夹,但没有运气。任何人都能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

根据Trying to upload files to subfolder in Sharepoint Online via Powershell您需要修改FileCreationURL:

$FileCreationInfo.URL = $List.RootFolder.ServerRelativeUrl + "/" + $FolderName + "/" + $File.Name

我相信您只需要将$ File.Name与文件夹路径一起添加到根目录。

Web.GetFolderByServerRelativeUrl方法:

或者尝试通过List.RootFolder上传...,您可以使用“GetFolderByServerRelativeUrl”方法获取目标文件夹

$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder) 
$Context.ExecuteQuery()
$FolderName = "Sales"

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

然后上传你会使用

$FileCreationInfo.URL = $File.Name
$UploadFile = $TargetFolder.Files.Add($FileCreationInfo)
$Context.Load($UploadFile)
$Context.ExecuteQuery()