如何使用 Powershell System.Net.WebClient 和自定义用户代理字符串下载文件?

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

我运行下面的命令使用PowershellSystem.Net.WebClient方法下载一个文件:

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

有没有办法自定义用户代理并保留单行命令格式?

我问的原因是因为该网站将请求识别为来自机器人,并且我收到 HTTP 403 禁止错误。当我使用 Internet Explorer 时,我可以毫无问题地下载文件。我想保留单行格式,因为此命令是从 Windows.

中的批处理 (.bat) 文件调用的

此代码片段将与 webclient 一起执行自定义用户代理部分:

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