Skip to content

Instantly share code, notes, and snippets.

@TheBigBear
Last active February 8, 2023 10:53
Show Gist options
  • Save TheBigBear/68510c4e8891f43904d1 to your computer and use it in GitHub Desktop.
Save TheBigBear/68510c4e8891f43904d1 to your computer and use it in GitHub Desktop.
get a file from web URL and figure out it's filename

I am trying to get a powershell script that I can call with one (or two) params.

Ideally I would like to pass only one paramter, the $Url and expect the script to figure out the filename and then download to that filename.

IF it does not figure out a filename, I can optionally pass a second parameter the $FolderPath

# get-FileFromUri.ps1
function get-FileFromUri {
  param(
    [Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
    [string]
    [Alias('Uri')]
    $Url,
    [Parameter(Mandatory = $false,Position = 1)]
    [string]
    [Alias('Folder')]
    $FolderPath
  )
  process {
    try {
      # resolve short URLs
      $req = [System.Net.HttpWebRequest]::Create($Url)
      $req.Method = "HEAD"
      $response = $req.GetResponse()
      $fUri = $response.ResponseUri
      $filename = [System.IO.Path]::GetFileName($fUri.LocalPath);
      $response.Close()
      # download file
      $destination = (Get-Item -Path ".\" -Verbose).FullName
      if ($FolderPath) { $destination = $FolderPath }
      if ($destination.EndsWith('\')) {
        $destination += $filename
      } else {
        $destination += '\' + $filename
      }
      $webclient = New-Object System.Net.webclient
      $webclient.downloadfile($fUri.AbsoluteUri,$destination)
      Write-Host -ForegroundColor DarkGreen "downloaded '$($fUri.AbsoluteUri)' to '$($destination)'"
    } catch {
      Write-Host -ForegroundColor DarkRed $_.Exception.Message
    }
  }
}

get-FileFromUri $Url $FolderPath

But this script does not seem to work? If i call it absolutely nothing useful seems to happen? Where did I go wrong? I call it from a powershell prompt as

.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip'

But I get :

.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip'
get-FileFromUri : Cannot bind argument to parameter 'Url' because it is an empty string.
At .\get-FileFromUri.ps1:39 char:17
+ get-FileFromUri $Url $FolderPath
+                 ~~~~
    + CategoryInfo          : InvalidData: (:) [get-FileFromUri], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,get-FileFromUri

How do I pass my params to this script? A simple wget in *nix gives me the file. and even giving it a filename as second argument has seemingly no effect. How do I improve this, so it takes paramters and actually calls the function with those two params pased on the cmd line?

.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip' 'c:\temp\myfile1.zip'
function get-FileFromUri {
param(
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[string]
[Alias('Uri')]
$Url,
[Parameter(Mandatory = $false,Position = 1)]
[string]
[Alias('Folder')]
$FolderPath
)
process {
try {
# resolve short URLs
$req = [System.Net.HttpWebRequest]::Create($Url)
$req.Method = "HEAD"
$response = $req.GetResponse()
$fUri = $response.ResponseUri
$filename = [System.IO.Path]::GetFileName($fUri.LocalPath);
$response.Close()
# download file
$destination = (Get-Item -Path ".\" -Verbose).FullName
if ($FolderPath) { $destination = $FolderPath }
if ($destination.EndsWith('\')) {
$destination += $filename
} else {
$destination += '\' + $filename
}
$webclient = New-Object System.Net.webclient
$webclient.downloadfile($fUri.AbsoluteUri,$destination)
Write-Host -ForegroundColor DarkGreen "downloaded '$($fUri.AbsoluteUri)' to '$($destination)'"
} catch {
Write-Host -ForegroundColor DarkRed $_.Exception.Message
}
}
}
get-FileFromUri $Url $FolderPath
@TheBigBear
Copy link
Author

OK so I added -ArgumentList whe calling it, as in

.\get-FileFromUri.ps1 -ArgumentList 'http://www.mywebsite.com/downloads/myfile1.zip','c:\temp\myfile1.zip'

and I stil get seemingly same error:

powershell -c .\get-FileFromUri.ps1 -ArgumentList 'http://www.mywebsite.com/downloads/myfile1.zip','c:\temp\myfile1.zip'
get-FileFromUri : Cannot bind argument to parameter 'Url' because it is an empty string.
At .\get-FileFromUri.ps1:39 char:17
+ get-FileFromUri $Url $FolderPath
+                 ~~~~
    + CategoryInfo          : InvalidData: (:) [get-FileFromUri], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,get-FileFromUri

@he852100
Copy link

he852100 commented Nov 1, 2019

add

[string]$Url,
[string]$FolderPath
get-FileFromUri $Url $FolderPath

Perform

. "C:\Users\Administrator\222.ps1" "https://software-download.microsoft.com/pr/Win10_1903_V2_Chinese(Simplified)_x64.iso?t=9ad57096-ee57-4654-af00-9c7c83a73e06&e=1572662065&h0defb92822050789122e4b52f0a00f4c"

or

param(
    [Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
    [string]
    $Url,
    [Parameter(Mandatory = $false,Position = 1)]
    [string]
    [Alias('Folder')]
    $FolderPath
  )
  process {
    try {
      # resolve short URLs
      $req = [System.Net.HttpWebRequest]::Create($Url)
      $req.Method = "HEAD"
      $response = $req.GetResponse()
      $fUri = $response.ResponseUri
      $filename = [System.IO.Path]::GetFileName($fUri.LocalPath);
      $response.Close()
      # download file
      $destination = (Get-Item -Path ".\" -Verbose).FullName
      if ($FolderPath) { $destination = $FolderPath }
      if ($destination.EndsWith('\')) {
        $destination += $filename
      } else {
        $destination += '\' + $filename
      }
      $webclient = New-Object System.Net.webclient
      $webclient.downloadfile($fUri.AbsoluteUri,$destination)
      Write-Host -ForegroundColor DarkGreen "downloaded '$($fUri.AbsoluteUri)' to '$($destination)'"
    } catch {
      Write-Host -ForegroundColor DarkRed $_.Exception.Message
    }
  }

Perform

. "C:\Users\Administrator\222.ps1" "https://software-download.microsoft.com/pr/Win10_1903_V2_Chinese(Simplified)_x64.iso?t=9ad57096-ee57-4654-af00-9c7c83a73e06&e=1572662065&h=0defb92822050789122e4b52f0a00f4c"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment