PowerShell - Download file(s) from URL that does not include file name in the URL

24,649

Solution 1

$source = "http://www.website.com/file/someFile.txt"
$Filename = [System.IO.Path]::GetFileName($source)
$dest = "C:\Users\Charles\Desktop\Downloads\$Filename"

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($source, $dest)

Solution 2

I got the same error as you described when I called:

$source = "http://www.website.com/file/[fileID]"
$dest = "C:\Users\Charles\Desktop\Downloads\"

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($source, $dest)

But when I changed $dest to contain the full path(including the name of the file it worked)

$dest = "C:\Users\Charles\Desktop\Downloads\[aFileName]"
Share:
24,649
Admin
Author by

Admin

Updated on April 20, 2020

Comments

  • Admin
    Admin about 4 years

    I've searched around and tried a few things and have not gotten it to work. The link would be for example: http://www.website com/file/[fileID] (e.g. http://www.website com/file/1wA5fT) and a box would appear whether to save the file(s) or not.

    I have tried this, from what I can remember and it did not work.

    $source = "http://www.website.com/file/[fileID]"
    $dest = "C:\Users\Charles\Desktop\Downloads\"
    
    $wc = New-Object System.Net.WebClient
    $wc.DownloadFile($source, $dest)
    

    Edit:

    I am able to correctly download the file if I put a filename for the destination. However I need to extract the filename from e.g.

    <a href="http://www.website.com/file/[fileID]">Filename.txt</a></li></div></ul>

    After I get this singled out how would I single out the filename into $Filename?

    $source = "http://www.website.com/file/[fileID]"
    $dest = "C:\Users\Charles\Desktop\Downloads\$Filename"
    
    $wc = New-Object System.Net.WebClient
    $wc.DownloadFile($source, $dest)
    

    This code would work then.