2

There's a few questions floating around for how to download files with PowerShell. I'm using PowerShell Core, so I cannot use my favorite method anymore: Start-BitsTransfer.

I see this recommended:

Invoke-WebRequest URL -OutFile c:\file.ext

However it seems suboptimal to have to give the file name. Can PowerShell/iwr guess the file name based on the URL path or the response headers?

I tried Invoke-WebRequest URL alone, but that doesn't store the file at all. From reading the docs it looks like there may be no option for that, is that correct? Is there a different one-liner in PowerShell to download a file using its original file name?

1

1 Answer 1

2

There is not a switch for Invoke-WebRequest. The following code will work, however, to extract the name from the filepath in a single line:

Invoke-WebRequest $URL -OutFile "C:\$(Split-Path -Leaf $URL)"

Split-Path will take a path and return either the full path to the parent container with -Parent argument, or the name of the file/directory at the end with the -Leaf argument.

However, this only works if the filename is part of the URL. If you, for example, have something like http://server.domain.tld/download.php?id=12345, the output file would end up being download.php?id=12345. It's not a one liner, but @Theo shared an answer in his comment that defines a function to get the redirected URL. You can then use Split-Path -Leaf on that redirected URL to get the desired filename.

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunate, thanks for the answer. PowerShell seems to have a good number of really head-scratching omissions/oddities which really grind my gears.
Eh, IMO this is a minor inconvenience to have to name the file. I agree it would be nice if it could try guessing the name but in most cases (for me) I end up giving files specific names for the sake of idempotency.
WARNING: If you don't trim() the trailing newline from the Split-Path subcommand, it could cause a Illegal characters in path error from Invoke-WebRequest. For more info, see Invoke-WebRequest Error: "Illegal characters in path" when using OutFile Split-Path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.