0

Setting up some CI stuff. I need a one-liner powershell command to download a file with basic authentication from a server.

I'm able to do it with an unauthenticated request like so:

iex ((New-Object Net.Webclient).DownloadString('http://myhost.example/resource.etc'))

How would I do the same but with authentication? From How to make an authenticated web request in Powershell?, I can see I need a NetworkCredential, just trying to figure out how to condense this to a single command.

Cinder Biscuits
  • 4,880
  • 31
  • 51
  • 2
    If you really want a single line you can use `Invoke-RestMethod` and stuff the Base64 conversion of the credentials in one expression. Won't win any beauty contests, but hey. In general, if you really want one-liners at the end, you'd be better off writing your own cmdlets, putting those in a script and making sure it's imported by your CI pipeline, so you have these available globally. This will also prevent a ton of copy-pasting otherwise cryptic one-liners (good luck changing those everywhere if there's a mistake). – Jeroen Mostert Nov 06 '19 at 14:03
  • 1
    The goal should be to document successful, repeatable processes. This enables others (and ourselves in 6 months) to be successful without reinventing the wheel. One-liners may be an interesting mental exercise, but they are far less valuable than easily read and understood code. – lit Nov 06 '19 at 14:09
  • This is all well and good but patronizing and not relevant to the question. Since apparently doing this in powershell would be an unintelligible mess (I find that hard to believe though), I will probably just use curl instead. – Cinder Biscuits Nov 06 '19 at 14:41
  • 1
    It highly [depends on what you consider "intelligible"](https://stackoverflow.com/a/58064211/4137916). (Just replace all the variables in there with their expressions, and there you go.) – Jeroen Mostert Nov 06 '19 at 14:45
  • 1
    See [this answer](https://stackoverflow.com/questions/24672760/powershells-invoke-restmethod-equivalent-of-curl-u-basic-authentication) for an example of how to get the Basic Auth header and use it in `Invoke-RestMethod`. `WebClient.Headers` can be added to, but can't be specified in the `New-Object -Property` Hashtable as far as I can tell. – Rich Moss Nov 07 '19 at 00:13

1 Answers1

1

This is how to download a string using authentication with a oneliner powershell

iex(((new-object System.Net.WebClient).Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)).DownloadString($url))