【问题标题】:How to get Location header when URL redirected using Invoke-WebRequest in powershell在powershell中使用Invoke-WebRequest重定向URL时如何获取位置标头
【发布时间】:2020-03-26 03:23:18
【问题描述】:
  • 调用永久移动或重定向的 URL,不会返回 Location http 标头或正确的位置。
  • 似乎在 URL 调用期间正在执行 URL 重定向(http 状态代码:302、301 等)。

我该如何克服这个问题?

【问题讨论】:

    标签: powershell redirect header location invoke-webrequest


    【解决方案1】:

    Alec Collier 找到 this answer

    将以下内容添加到您的 URL 调用中:-MaximumRedirection 0 -ErrorAction Ignore

    例子:

    $url="https://jigsaw.w3.org/HTTP/300/301.html"
    
    $resp = Invoke-WebRequest $url -MaximumRedirection 0 -ErrorAction Ignore
    
    $resp.Headers.Location
    

    【讨论】:

      【解决方案2】:

      只需使用-MaximumRedirection 0 -SkipHttpErrorCheck(如果您想取消警告,请添加-ErrorAction:SilentlyContinue):

      (Invoke-WebRequest -Uri "https://www.google.com/ncr" -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction:SilentlyContinue).Headers.Location
      
      https://www.google.com/
      

      注意返回值的数据类型是一个数组,它只有一个元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        • 1970-01-01
        • 2022-10-23
        • 1970-01-01
        • 2017-12-24
        相关资源
        最近更新 更多