PowerShell_Scripts/base/Invoke-WebDownload.ps1

45 lines
1.3 KiB
PowerShell

[CmdletBinding()]param(
[Parameter(Position=1)]
[string]$OutputPath,
[Parameter(Mandatory,Position=0,ValueFromPipeline)]
[string]$Url,
[switch]$Force,
[switch]$PassThru
)
process {
$local:outputFileName=[string]::Empty
if( -not $OutputPath ) {
$OutputPath = Join-Path $(Get-Item $PWD) ''
} elseif( Test-Path -Type Container $OutputPath ) {
$OutputPath = Join-Path $(Get-Item $OutputPath) ''
}
if( $OutputPath -notmatch '[/\\]$' ) {
$outputFileName = Split-Path -Leaf $OutputPath
$OutputPath = Join-Path $(Split-Path -Parent $OutputPath) ''
}
if( -not (Test-Path $OutputPath) -and $Force ) {
New-Item -Type Directory $OutputPath
}
if( -not (Test-Path $OutputPath) ) { throw "Destination $OutputPath does not exists, aborting!" }
if( -not $outputFileName ) {
$outputFileName = Split-Path -Leaf $Url
}
$outputFileName = Join-Path $OutputPath $outputFileName
if( (Test-Path $outputFileName) -and -not $Force) {
throw "$OutputFileName file already exists"
}
Write-Verbose "About to start download from:`n`t$Url`n`tto`n`t$outputFileName`n"
Invoke-WebRequest -Uri $Url -OutFile $outputFileName
if( $PassThru ) { Get-Item $outputFileName }
}