How to download a file with Powershell System.Net.WebClient and custom user-agent string?

slantalpha picture slantalpha · Jan 24, 2017 · Viewed 15.4k times · Source

I am running the following command to download a file using the Powershell System.Net.WebClient method:

powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://domain.name/file.name','C:\file.name')"

Is there a way to customize the user-agent and to also retain the one-line command format?

Reason I'm asking is because the website recognizes the request as coming from a bot, and I'm getting an HTTP 403 forbidden error. When I use Internet Explorer, I can download the file without issues. I'd like to keep the one-line format because this command is being called from a batch (.bat) file in Windows.

Answer

ClumsyPuffin picture ClumsyPuffin · Jan 24, 2017

This code snippet will perform the custom user agent part along with webclient :

powershell -command {
    $cli = New-Object System.Net.WebClient;
    $cli.Headers['User-Agent'] = 'myUserAgentString';
    $cli.DownloadFile('https://domain.name/file.name', 'C:\file.name')
}