PowerShell Invoke-WebRequest,如何自动使用原始文件名? [英] PowerShell Invoke-WebRequest, how to automatically use original file name?

查看:64
本文介绍了PowerShell Invoke-WebRequest,如何自动使用原始文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Invoke-WebRequest 下载文件但自动使文件名与通过浏览器下载的文件名相同?我还没有找到一种无需手动指定文件名就可以使 -OutFile 工作的方法.我对这涉及其他几行代码没问题.

How can I use Invoke-WebRequest to download a file but automatically make the file name the same as if I downloaded via browser? I haven't found a way to make -OutFile work without manually specifying the file name. I'm fine with this involving a few other lines of code.

一个好的解决方案将:

  • 即使文件名不在请求 URL 中也能工作.例如,下载 Visual Studio x64 远程调试工具的 URL 是 http://go.microsoft.com/fwlink/?LinkId=393217 但它下载文件 rtools_setup_x64.exe.
  • 在写入磁盘之前不要将整个文件保存到内存中,除非即使使用 -OutFile 参数 (?),Invoke-WebRequest 也已经这样做了

谢谢!

推荐答案

对于给出的示例,您将需要获取重定向的 URL,其中包括要下载的文件名.您可以使用以下函数来执行此操作:

For the example given you're going to need to get the redirected URL, which includes the file name to be downloaded. You can use the following function to do so:

Function Get-RedirectedUrl {

    Param (
        [Parameter(Mandatory=$true)]
        [String]$URL
    )

    $request = [System.Net.WebRequest]::Create($url)
    $request.AllowAutoRedirect=$false
    $response=$request.GetResponse()

    If ($response.StatusCode -eq "Found")
    {
        $response.GetResponseHeader("Location")
    }
}

然后是从响应 URL 的末尾解析文件名的问题(来自 System.IO.Path 的 GetFileName 会这样做):

Then it's a matter of parsing the file name from the end of the responding URL (GetFileName from System.IO.Path will do that):

$FileName = [System.IO.Path]::GetFileName((Get-RedirectedUrl "http://go.microsoft.com/fwlink/?LinkId=393217"))

这将留下 $FileName = rtools_setup_x64.exe,您应该可以从那里下载您的文件.

That will leave $FileName = rtools_setup_x64.exe and you should be able to download your file from there.

这篇关于PowerShell Invoke-WebRequest,如何自动使用原始文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆