2017-03-08 53 views
1

上傳到SharepointOnline子文件夾,似乎我可以將文件上載到SPO的網站集URL而不是子文件夾。例如,我可以上傳到「https://xyz.sharepoint.com/sites/Reporting」,但不能「https://xyz.sharepoint.com/sites/Reporting/Sales」。這裏是工作的代碼的相關位:使用Powershell

$Username = "[email protected]" 
$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() 

我試圖硬編碼「/銷售」子文件夾,但沒有運氣。任何人都可以將我指向正確的方向?

回答

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() 
+0

我試圖設置$ FolderName =「Sales」,但它拋出一個錯誤異常調用「Execu teQuery「帶有」0「參數:」值不在預期範圍內「。 – rustynails

+0

設置後如何從$ FileCreationInfo.URL中獲得什麼輸出? – dwarfsoft

+0

URL:「/Reporting/Sales/Foo.txt」。我猜它缺少sharepoint.com之前的URL? Foo.txt是我的測試文件 – rustynails