wget for PowerShell

[new] Update: You should look at this other WGet for PowerShell script if what you want is to just download a file and have it work…

I’m probably the last person on the planet to figure out how easy it is to get a basic wget working in PowerShell … but just in case I’m not … here’s a PowerShell script which will download web files to your hard drive.

That’s all it does. This script doesn’t support authentication or anything (even though it does use your computer’s proxy settings), but I think it will be obvious how to extend it, since it’s basically just .Net Framework stuff.

param([string]$url, [string]$path)

if(!(Split-Path -parent $path) -or !(Test-Path -pathType Container (Split-Path -parent $path))) {
  $path = Join-Path $pwd (Split-Path -leaf $path)

"Downloading [$url]`nSaving at [$path]"

$client = new-object System.Net.WebClient
$client.DownloadFile( $url, $path )

That’s all there is to it. Actually, you really only need the last two lines (and the first line), as long as you understand that the default path will be your user directory rather than the current directory. (like: C:\Users\Joel OR C:\Documents and Settings\Joel\). That means that if you leave off that if(!(Split-Path -parent $path)) stuff, you’ll always have to specify the file starting with a .\ if you want it saved in the folder you’re in (otherwise it gets dumped in your user directory).

Those three lines check if the specified path has a folder in it (and if it’s a valid folder) and if not, they just save the file to the local current folder.

Here are some examples of how you’d use it, assuming you save that into a file called “wget.ps1” and put it in your path. Incidentally, just like in ‘nix shells, ~ represents your user directory … oh, and the generally more PowerShell-like name for the script would be “Get-Url.ps1” or something…

  • wget http://huddledmasses.org/downloads/RunOnlyOne.exe RunOnlyOne.exe
  • wget http://huddledmasses.org/downloads/RunOnlyOne.exe .\RunOne.exe
  • wget http://huddledmasses.org/downloads/RunOnlyOne.exe ~\RunOnly1.exe

If anyone can tell me how to figure out what the file name should be when the URL ends with something like: .../download.php?file=361 I’ll post an amendment here that will let you skip specifying the file name.

Similar Posts:

2 thoughts on “wget for PowerShell”

  1. Yeah, but it’s not just a matter of path parsing… a lot of download sites obscure the file name somewhat by using a URL like domain.com/Downloads/ProjectReleases.aspx?ReleaseId=6426 using system.uri to try to get the file name would have you saving a .zip file as “ProjectReleases.aspx” ...

Comments are closed.