|
| 1 | +function Get-HttpResource { |
| 2 | +<# |
| 3 | +.SYNOPSIS |
| 4 | +Downloads the contents from a URL |
| 5 | +
|
| 6 | +.DESCRIPTION |
| 7 | +Get-HttpResource downloads the contents of an HTTP url. |
| 8 | +When -PassThru is specified it returns the string content. |
| 9 | +
|
| 10 | +.PARAMETER Url |
| 11 | +The url containing the content to download. |
| 12 | +
|
| 13 | +.PARAMETER OutputPath |
| 14 | +If provided, the content will be saved to this path. |
| 15 | +
|
| 16 | +.PARAMETER PassThru |
| 17 | +If provided, the string will be output to the pipeline. |
| 18 | +
|
| 19 | +.EXAMPLE |
| 20 | +$content = Get-HttpResource -Url 'http://my/url' ` |
| 21 | + -OutputPath 'c:\myfile.txt' ` |
| 22 | + -PassThru |
| 23 | +
|
| 24 | +This downloads the content located at http://my/url and |
| 25 | +saves it to a file at c:\myfile.txt and also returns |
| 26 | +the downloaded string. |
| 27 | +
|
| 28 | +.LINK |
| 29 | +http://boxstarter.org |
| 30 | +
|
| 31 | +#> |
| 32 | + param ( |
| 33 | + [string]$Url, |
| 34 | + [string]$OutputPath = $null, |
| 35 | + [switch]$PassThru |
| 36 | + ) |
| 37 | + Write-BoxstarterMessage "Downloading $url" -Verbose |
| 38 | + $str = Invoke-RetriableScript -RetryScript { |
| 39 | + $downloader=new-object net.webclient |
| 40 | + $wp=[system.net.WebProxy]::GetDefaultProxy() |
| 41 | + $wp.UseDefaultCredentials=$true |
| 42 | + $downloader.Proxy=$wp |
| 43 | + try { |
| 44 | + $httpString = $downloader.DownloadString($args[0]) |
| 45 | + if($args[1]) { |
| 46 | + Write-BoxstarterMessage "Saving $httpString to $($args[1])" -Verbose |
| 47 | + if(Test-Path $args[1]){Remove-Item $args[1] -Force} |
| 48 | + $httpString | Out-File -FilePath $args[1] -Encoding utf8 |
| 49 | + } |
| 50 | + $httpString |
| 51 | + } |
| 52 | + catch{ |
| 53 | + if($VerbosePreference -eq "Continue"){ |
| 54 | + Write-Error $($_.Exception | fl * -Force | Out-String) |
| 55 | + } |
| 56 | + throw $_ |
| 57 | + } |
| 58 | + } $Url $OutputPath |
| 59 | + |
| 60 | + if($PassThru) { Write-Output $str } |
| 61 | +} |
0 commit comments