Patch/Cmdlets/Misc/Save-DownloadedFile.ps1
<#
.SYNOPSIS Download a file from Uri to a folder preserving the file name server by web service. .DESCRIPTION Download a file from Uri to a folder preserving the file name server by web service. .EXAMPLE Save-Download -Uri "http://localhost:8090/dd2408e8-a60c-4e5a-b8de-64adedf46802" -Directory "C:\temp" #> function Save-DownloadedFile { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline)] $WebResponse, [Parameter(Mandatory = $true)] [string] $Directory ) process { $errorMessage = "Cannot determine filename for download." if (!($WebResponse.Headers.ContainsKey("Content-Disposition"))) { Write-Error "$errorMessage Response Header not found." -ErrorAction Stop } $content = [System.Net.Mime.ContentDisposition]::new($WebResponse.Headers["Content-Disposition"]) $fileName = $content.FileName if (!$fileName) { Write-Error "$errorMessage File name is empty." -ErrorAction Stop } if (!(Test-Path -Path $Directory)) { New-Item -Path $Directory -ItemType Directory } $fullPath = Join-Path -Path $Directory -ChildPath $fileName Write-Verbose "Downloading to $fullPath" $file = [System.IO.FileStream]::new($fullPath, [System.IO.FileMode]::Create) $file.Write($WebResponse.Content, 0, $WebResponse.RawContentLength) $file.Close() } } |