使用PowerShell从SharePoint Online下载文件
我需要使用powershell从sharepoint在线文档库下载文件 我已经设法达到了应该下载的程度,但是运气不好 我知道这与我如何使用流/编写器有关 如有任何提示,将不胜感激 *编辑 不会抛出任何错误消息,只会在我的本地目录中抛出0个长度的文件使用PowerShell从SharePoint Online下载文件,sharepoint,powershell-3.0,csom,Sharepoint,Powershell 3.0,Csom,我需要使用powershell从sharepoint在线文档库下载文件 我已经设法达到了应该下载的程度,但是运气不好 我知道这与我如何使用流/编写器有关 如有任何提示,将不胜感激 *编辑 不会抛出任何错误消息,只会在我的本地目录中抛出0个长度的文件 $SPClient = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") $SPRuntime = [System.Reflection
$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()
}虽然上面的CSOM代码可能可以正常工作,但我发现使用web客户端方法更容易 (来自) 我使用了下面的代码,将一组文件(CSOM查询中的元数据)检索到一个文件夹(使用$result集合,其他参数应该稍微调整一下): 这里的诀窍是 $client.UseDefaultCredentials=$true
这将为您(作为当前用户)验证webclient。因此我放弃了这一点。事实证明,编写SSIS脚本组件来完成这项工作要容易得多。 我已经奖励了Soeren,因为他发布了一些代码,这些代码将适用于常规网站,但不会覆盖SharePoint Online
谢谢你,索林 我使用以下相关代码片段成功下载了该文件。你应该能够根据自己的情况扩展它
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();
您还可以通过提供从SharePoint Online下载资源,如下所示
先决条件
必须安装在运行脚本的计算机上
如何在PowerShell中的SharePoint Online/O365中下载文件
下载文件.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()
}
用法
对于这个问题,最直接、最简短的回答是:
$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中有效…简而言之,这是一种从sharepoint online下载文件的简单方法,只需使用Powershell和sharepoint online url即可(无pnp Powershell) 此方法也可用于执行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
是目标sp站点url$targetSiteUrl
是“[sharepoint文件完整url]”$spFileUrl
纯文本sp用户电子邮件$user
纯文本sp用户通行证$pass
Create
。您可能还需要将Create参数实例化为System.IO.filemode对象,有时候,仅仅传递一个字符串对这些不起作用。我已经做了@JNK建议的更改,得到了相同的结果。没有错误,仅本地0个长度的文件。我也尝试过System.Net.WebClient,但SharePoint Online似乎需要SharePoint客户端进行身份验证。我认为这与不知道要下载的文件大小或不在流上循环有关。。我真的很迷茫,这是一个更接近sharepoint的在线网站,但我尝试了webclient,总是得到一个403。它必须使用SharePointClientThank亲爱的。。!它拯救了我的一天。。!!然而,我对sharepoint online尝试了这种方法,但我无法正确地进行身份验证。我已经介绍了从sharepoint Onlinet下载文件的完整方法(谢谢:)这对我来说是一辈子以前的事了,但我100%相信其他人会发现它很有用
$url = 'https://the.server/path/to/the/file.txt'
$outfile = "$env:userprofile\file.txt"
Invoke-WebRequest -Uri $url -OutFile $outfile -Credential (Get-Credential)
# 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