3

我需要使用 powershell 从共享点在线文档库下载文件

我已经设法达到下载应该发生但没有运气的地步。

我知道这与我如何使用流/编写器有关

任何提示将不胜感激

*编辑在我的本地目录中只抛出 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()

}

4

6 回答 6

8

您还可以通过提供SharePoint Online 凭据来利用WebClient.DownloadFile 方法从 SharePoint Online 下载资源,如下所示。

先决条件

SharePoint Online 客户端组件 SDK必须安装在运行脚本的计算机上。

如何在 PowerShell 中下载 SharePoint Online/O365 中的文件

Download-File.ps1功能:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")


 Function Download-File([string]$UserName, [string]$Password,[string]$FileUrl,[string]$DownloadPath)
 {
    if([string]::IsNullOrEmpty($Password)) {
      $SecurePassword = Read-Host -Prompt "Enter the password" -AsSecureString 
    }
    else {
      $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
    }
    $fileName = [System.IO.Path]::GetFileName($FileUrl)
    $downloadFilePath = [System.IO.Path]::Combine($DownloadPath,$fileName)


    $client = New-Object System.Net.WebClient 
    $client.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
    $client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    $client.DownloadFile($FileUrl, $downloadFilePath)
    $client.Dispose()
}

用法

Download-File -UserName "username@contoso.onmicrosoft.com" -Password "passowrd" -FileUrl https://consoto.sharepoint.com/Shared Documents/SharePoint User Guide.docx -DownloadPath "c:\downloads"
于 2014-08-24T21:48:49.980 回答
6

我能够使用以下相关代码片段成功下载文件。您应该能够根据您的情况扩展它。

Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$siteUrl = Read-Host -Prompt "Enter web URL"
$username = Read-Host -Prompt "Enter your username"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$source = "/filepath/sourcefilename.dat" #server relative URL here
$target = "C:/detinationfilename.dat" #URI of the file locally stored

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials

[Microsoft.SharePoint.Client.FileInformation] $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx,$source);
[System.IO.FileStream] $writeStream = [System.IO.File]::Open($target,[System.IO.FileMode]::Create);

$fileInfo.Stream.CopyTo($writeStream);
$writeStream.Close();
于 2013-11-28T04:33:55.437 回答
4

虽然上面的 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

这将为您(作为当前用户)验证网络客户端。

于 2013-09-23T10:52:58.017 回答
1

所以我放弃了这个。事实证明,编写一个 SSIS 脚本组件来完成这项工作要容易得多。我已授予 Soeren,因为他发布了一些适用于常规网站但不适用于 SharePoint Online 的代码。

谢谢索伦!

于 2013-09-25T12:56:44.777 回答
1

该问题的直接且几乎最短的答案很简单:

$url = 'https://the.server/path/to/the/file.txt'
$outfile = "$env:userprofile\file.txt"
Invoke-WebRequest -Uri $url -OutFile $outfile -Credential (Get-Credential)

这至少在 Powershell 5.1 中有效......

于 2018-04-15T18:03:44.997 回答
1

简而言之,只需使用 powershell 和 sharepoint online url (无 pnp powershell)从 sharepoint 在线下载文件的简单方法

这种方法也可用于执行 Sharepoint REST 查询,只需 powershell 和 sharepoint REST api

# required MS dependencies
# feel free to download them from here https://www.microsoft.com/en-us/download/details.aspx?id=42038

Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll' -ErrorAction Stop
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll' -ErrorAction Stop

# prepare passwords
$spCredential = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($user, $(ConvertTo-SecureString -AsPlainText $pass -Force))
    
# prepare and perform rest api query
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($targetSiteUrl)
$Context.Credentials = $spCredential
    try {
        #this may return an error, but still will finish context setup
        $Context.ExecuteQuery()    
    }
    catch {
        write-host "TODO: fix executeQuery() err 400 bug" -ForegroundColor Yellow
    }
$AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($targetSiteUrl, $true)
    
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Credentials = $Context.Credentials
$WebSession.Cookies.SetCookies($targetSiteUrl, $AuthenticationCookie)
$WebSession.Headers.Add("Accept", "application/json;odata=verbose")

Invoke-WebRequest  -Uri $spFileUrl -OutFile $outputFilePath -WebSession $WebSession -errorAction Stop

在哪里

  • $outputFilePath是要保存远程文件的目标输出文件。
  • $targetSiteUrl是目标 sp 站点 url。
  • $spFileUrl是“[sharepoint 文件完整 url]”
  • $user纯文本 sp 用户电子邮件
  • $pass纯文本 sp 用户通行证
于 2021-02-10T11:41:34.870 回答