Search code examples
powershellhttpbatch-fileuser-agentsystem.net

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


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.


Solution

  • 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')
    }