如何将文件从SharePoint团队网站导入本地计算机?

时间:2017-01-11 09:18:56

标签: powershell sharepoint

我的客户端每月生成报告(excel文件),并将文件上载到SharePoint文档库中。一些报告再次通过邮件(outlook)传出。

要求是我们需要将excel报告(在文档库中以及通过邮件发送的文件)复制到登陆区域(FTP服务器),我们需要每个月自动执行此过程。

实现这一目标的最佳方式是什么?请帮帮我。谢谢..

1 个答案:

答案 0 :(得分:0)

$uri = "https://intranet.company.com/departments/SampleSite/_api/web/getfilebyserverrelativeurl('/departments/SampleSite/Shared Documents/test.docx')/`$Value"
$FileBinary = $(Invoke-WebRequest -Uri $uri -Credential $cred -ContentType 'application/json;odata=verbose').Content
[System.IO.File]::WriteAllBytes('C:\tempfolder\test.docx',$FileBinary)

使用此示例,您可以下载文件并保存(它使用SP REST API)。此简单示例使用当前登录用户的凭据。

编辑:根据请求,我已为SharePoint Online添加了一个示例(由于登录流程,您需要SP SDK)。代码没有优化,因为这是我的第一个样本之一。问题是你必须“硬编码”凭据。我在公司内部的解决方案是使用证书加密凭证:我使用运行脚本的服务帐户的公钥加密文件中的凭据;服务帐户使用私钥对其进行解密。不理想但对我们来说足够安全。

$cred = Get-Credential # Get credentials

## Load the Assemblies
add-type -AssemblyName system.net.http
Add-type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

# Put credentials in SPO credential object
$SPCred = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($cred.UserName,$cred.Password)
# Set the uri's
$uri = [uri]::new('https://YourTentant.sharepoint.com')
$fullUri = "https://YourTentant.sharepoint.com/sites/ApiTest/_api/web/getfilebyserverrelativeurl('/sites/ApiTest/Shared Documents/Document.docx')/`$Value"
# Create HTTPClientHandler object and set the properties
$handler = [System.Net.Http.HttpClientHandler]::new()
$handler.Credentials = $SPCred
$handler.CookieContainer.SetCookies($uri,$SPCred.GetAuthenticationCookie($uri))

# Create the client and set the options
$Client = [System.Net.Http.HttpClient]::new($handler)
$Client.DefaultRequestHeaders.Accept.Clear()
$Client.DefaultRequestHeaders.Accept.Add([System.Net.Http.Headers.MediaTypeWithQualityHeaderValue]::new('application/json'))
# Call the URL (async) and get the response
$Response = $Client.GetAsync($fullUri)
$data = $Response.Result

## now download the data as string (in the final version I'm going to call the ReadAsStream() method instead to get the binary file)
$a = $data.Content.ReadAsStringAsync() 
$a.Result