5

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.

Charles Feemster
  • 51
  • 1
  • 1
  • 3
  • What error message did you receive when you tried that? – E.Z. Hart Oct 08 '12 at 21:20
  • 1
    `Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request." At line:5 char:17 + $wc.DownloadFile <<<< ($source, $dest) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException` – Charles Feemster Oct 08 '12 at 22:14
  • 1
    Can you provide an example URL? I am guessing that it should be similar to MS download URLs that redirect you to the file. In such a case, you need to retrieve and use the redirected URL. – ravikanth Oct 09 '12 at 06:14
  • related, not in PowerShell, but good explanation on what's going with a working example using `curl`: [curl-to-grab-remote-filename-after-following-location](http://stackoverflow.com/questions/6881034/curl-to-grab-remote-filename-after-following-location) – Marijn May 16 '13 at 20:27

2 Answers2

19
$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)
Bob Reynolds
  • 550
  • 6
  • 8
  • 1
    +1 for showing that [GetFileName](http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx) can parse URLs! It's awesome that PowerShell has the the whole .NET library at its disposal, but you can't use it if you don't know about it! – Iain Samuel McLean Elder Apr 14 '13 at 16:35
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]"
toftis
  • 1,070
  • 9
  • 26