使用PowerShell从SharePoint Online下载文件

Maxui

我需要使用Powershell从SharePoint在线文档库中下载文件

我设法到达应该进行下载但没有运气的地步。

我知道这与我使用流/编写器的方式有关

任何提示将不胜感激

*编辑在我的本地目录中没有错误消息仅引发长度为0的文件

$SPClient =  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$SPRuntime = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

$webUrl =  Read-Host -Prompt "HTTPS URL for your SP Online 2013 site" 
$username = Read-Host -Prompt "Email address for logging into that site" 
$password = Read-Host -Prompt "Password for $username" -AsSecureString
$folder = "PoSHTest" 
$destination = "C:\\test"

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) 
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$web = $ctx.Web
$lists = $web.Lists.GetByTitle($folder)
$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(10000) 
$result = $lists.GetItems($query)
$ctx.Load($Lists)
$ctx.Load($result)
$ctx.ExecuteQuery()

#Edited the foreach as per @JNK
foreach ($File in $result) {
         Write-host "Url: $($File["FileRef"]), title: $($File["FileLeafRef"]) "
        $binary = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx,$File["FileRef"])
        $Action = [System.IO.FileMode]::Create 
        $new = $destination + "\\" + $File["FileLeafRef"]
        $stream = New-Object System.IO.FileStream $new, $Action 
        $writer = New-Object System.IO.BinaryWriter($stream)
        $writer.write($binary)
        $writer.Close()

}

索伦·尼尔森(Soeren L.Nielsen)

虽然上面的CSOM代码可能可以工作,但我发现使用Web客户端方法更容易。

(摘自http://soerennielsen.wordpress.com/2013/08/25/use-csom-from-powershell/

我使用下面的代码将一堆文件(来自CSOM查询的元数据)检索到一个文件夹(使用$ result集合,应该对其他参数进行一些调整):

#$siteUrlString site collection url
#$outPath path to export directory


$siteUri = [Uri]$siteUrlString
$client = new-object System.Net.WebClient
$client.UseDefaultCredentials=$true

if ( -not (Test-Path $outPath) ) {
    New-Item $outPath -Type Directory  | Out-Null
}

$result |% {
    $url = new-object Uri($siteUri, $_["FileRef"])
    $fileName = $_["FileLeafRef"]
    $outFile = Join-Path $outPath $fileName
    Write-Host "Downloading $url to $outFile"

    try{
        $client.DownloadFile( $url, $outFile )      
    }
    catch{
        #one simple retry...
        try{
            $client.DownloadFile( $url, $outFile )      
        }
        catch{
            write-error "Failed to download $url, $_"
        }
    }
}   

这里的窍门是$ client.UseDefaultCredentials = $ true

它将为您(作为当前用户)验证Web客户端。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章