PS – download of csv-files of a folder from Sharepoint via webclient

In this example the assumption is that you don´t have a Sharepoint server on which you could use the Sharepoint commandlets. So only the standard webclient functions were used to allow you to download all files. Also you need some valid credentials to log onto the Sharepoint website otherwise you would get the error 401 (not authorized).

Here is the code herefore:


<# 
.Synopsis 
Download all files from a sharepoint folder. 
.DESCRIPTION 
download all files from a sharepoint aspx-site. 
.EXAMPLE 
$credentials=Get-Credential -Credential Domäne\Benutzer 
[string]$sharepointURL = 'https://domäne.de/ExportOrdner/Forms/Overview.aspx' Download-AllFilesFromSP -SP_ASPX_Page $sharepointURL -DestinationFolder 'C:\ExportDirectory' -Credentials $credentials 
.INPUTS SP_ASPX_Page - aspx-site DestinationFolder target  CredentialsSP - authentication 
.FUNCTIONALITY 
Web; Sharepoint; Download 
#>
  function Download-AllCSVFilesFromSP
        {
            PARAM (
                [parameter(Mandatory=$true)]
                $SP_ASPX_Page,
                [parameter(Mandatory=$true)]
                $DestinationFolder,
                [parameter(Mandatory=$true)]
                $CredentialsSP
            )

            #create Object            
            $webclient = New-Object System.Net.WebClient 

            #set credentials
            $webclient.Credentials = $CredentialsSP 
            
            #retrieve content
            $response = Invoke-WebRequest -Uri $SP_ASPX_Page -Credential $CredentialsSP -Method Get

            #parse content parsen and search for export-files
            $matches =[regex]::Matches($response.content,'(\sUrl=\")+[0-9,a-z,A-Z\/_-]*(.csv\"\s)') 

            #foreach found file
            foreach ($item in $matches)
            {
                    #clean the download string             
                    $downloadFileURL = ($item.Groups[0].Value).Split('"')[1]

                    #extract the domain
                    $UrlDomain = ([regex]::Matches($SP_ASPX_Page,'https://[0-9,a-z,A-Z_\-\.]*')).Value

                    #extract filename
                    $downloadFile = $downloadFileURL.Split('/')[-1]
                    
                    #download to destination folder
                    $webclient.downloadfile($UrlDomain + $downloadFileURL,  $DestinationFolder + '\' + $downloadFile) 
            }
        }