powershell one liner to download file with credentials

10,485

If you are using PowerShell 3.0 or newer, you could try this:

<Path>powershell -NoLogo -Command "Invoke-WebRequest -Uri 'https://some.remote.private.location/myfile.ps1' -OutFile 'c:\Windows\Temp\myfile.ps1' -UseBasicParsing -Credential (New-Object PSCredential('user123', (ConvertTo-SecureString -AsPlainText -Force -String 'password123')))"</Path>

In PowerShell 2.0:

<Path>powershell -NoLogo -Command "$webClient = new-object System.Net.WebClient; $webClient.Credentials = new-object System.Net.NetworkCredential('user123', 'password123'); $webClient.DownloadFile('https://some.remote.private.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>
Share:
10,485
Quardah
Author by

Quardah

I like cats.

Updated on June 05, 2022

Comments

  • Quardah
    Quardah almost 2 years

    I am currently trying to instruct a newly created windows shell to download a powershell script via autounattend.xml file. With that technique, i need a one liner to get the job done.

    I used to be able to download them from a public environment using this one-liner :

    <Path>powershell -NoLogo -Command "((new-object System.Net.WebClient).DownloadFile('https://some.remote.public.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>
    

    But now i need to give in proper credentials to download my file from a private location. I tried the following and it doesn't work :

    <Path>powershell -NoLogo -Command "((new-object System.Net.WebClient).Credentials = new-object System.Net.NetworkCredential("user123", "password123")).DownloadFile('https://some.remote.private.location/myfile.ps1', 'c:\Windows\Temp\myfile.ps1')"</Path>
    

    (I'm a rookie in powershell :/)

    How can i give the proper credentials to the DownloadFile Method in a one liner?

    Or is there another command better suited for the job?

    Thanks.

  • Quardah
    Quardah almost 7 years
    Hi. Thanks for the quick reply. How do i know which powershell i am using? (It's with windows server 2012 R2 by the way). Can i use this command with "-EncodedCommand" also? Thanks.
  • Giorgi Chakhidze
    Giorgi Chakhidze almost 7 years
    @Quardah Server 2012 R2 comes with pre-installed version 4.0 of PowerShell (You can see version by printing $PSVersionTable variable). And yes, you can encode this command and pass it to -EncodedCommand.
  • Quardah
    Quardah almost 7 years
    Many, many thanks George i really appreciate the help. Have a nice day!