downloading a file from SharePoint Online with PowerShell

前端 未结 5 2062
终归单人心
终归单人心 2020-12-10 09:43

I have a requirement to download files from a sharepoint online document library using powershell

I\'ve managed to get to the point where the download should happen

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 10:05

    While the CSOM code above likely can be made to work I find it easier to use the web client method.

    (from http://soerennielsen.wordpress.com/2013/08/25/use-csom-from-powershell/)

    I've used the code below, to retrieve a bunch of files (metadata from CSOM queries) to a folder (using your $result collection, other params should be adjusted a bit):

    #$siteUrlString site collection url
    #$outPath path to export directory
    
    
    $siteUri = [Uri]$siteUrlString
    $client = new-object System.Net.WebClient
    $client.UseDefaultCredentials=$true
    
    if ( -not (Test-Path $outPath) ) {
        New-Item $outPath -Type Directory  | Out-Null
    }
    
    $result |% {
        $url = new-object Uri($siteUri, $_["FileRef"])
        $fileName = $_["FileLeafRef"]
        $outFile = Join-Path $outPath $fileName
        Write-Host "Downloading $url to $outFile"
    
        try{
            $client.DownloadFile( $url, $outFile )      
        }
        catch{
            #one simple retry...
            try{
                $client.DownloadFile( $url, $outFile )      
            }
            catch{
                write-error "Failed to download $url, $_"
            }
        }
    }   
    

    The trick here is the $client.UseDefaultCredentials=$true

    which will authenticate the webclient for you (as the current user).

提交回复
热议问题