如何使用Power Shell从Share Point列出文件system.net.webclient

时间:2019-12-04 15:14:46

标签: powershell sharepoint webclient

我可以使用System.net.webclient从在线共享点下载文件,但是在System.net.webclient类(https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient?view=netframework-4.8)中看不到任何相关方法来列出文件夹中的文件。以下是用于下载文件的代码段。在这里列出文件的任何帮助将不胜感激。

    $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)

1 个答案:

答案 0 :(得分:0)

我们需要使用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
}