【问题标题】:How to list files from Share Point using Power Shell | system.net.webclient如何使用 Powershell 从 Sharepoint 中列出文件 | system.net.webclient
【发布时间】:2019-12-05 17:56:52
【问题描述】:
我可以使用 System.net.webclient 从在线共享点下载文件,但是在 System.net.webclient 类 (https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient?view=netframework-4.8) 中没有看到任何相关方法来列出文件夹中的文件。下面是用于下载文件的代码 sn-p。在这里列出文件的任何帮助将不胜感激。
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $SecurePassword)
$wc.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
$wc.DownloadData($Source, $DownloadPath)
【问题讨论】:
标签:
powershell
sharepoint
webclient
【解决方案1】:
我们需要使用 CSOM 和 PowerShell 从 SharePoint 在线库中的文件夹中获取所有文件,然后使用 webclient 下载所有文件,以下示例代码供您参考。
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Setup Credentials to connect
#Config Variables
$SiteURL = "https://tenant.sharepoint.com/sites/team"
$UserName="test@tenant.onmicrosoft.com"
$Password ="password"
#Folder's Site Relative Path
$FolderURL= "Shared Documents/Subfolder"
$LocalPath="C:\temp\Subfolder"
#Get Credentials to connect
#$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#Get the Folder and Files
$Folder=$Ctx.Web.GetFolderByServerRelativeUrl($FolderURL)
$Ctx.Load($Folder)
$Ctx.Load($Folder.Files)
$Ctx.ExecuteQuery()
#Iterate through each File in the folder
Try
{
Foreach($File in $Folder.Files)
{
$wc = New-Object System.Net.WebClient
$wc.Credentials =$Credentials
$wc.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
$FilePath=$SiteURL+"/"+$FolderURL+"/"+$File.Name
$DownloadPath=$LocalPath+"\"+$File.Name
$wc.DownloadFile($FilePath, $DownloadPath)
$wc.Dispose()
}
}
catch
{
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}