简体   繁体   English

网址重定向时如何使用Powershell从Web下载文件

[英]How to download file from the web with Powershell when url redirects

I have seen downloading a file with the webclient for powershell. 我已经看到使用webclient下载文件以获取Powershell。 Problem is that the request url redirects multiple times before the actual file is presented. 问题在于,在显示实际文件之前,请求url会多次重定向。 it's an ssrs web interface with a query string meathod Download=bla.csv 这是一个带有查询字符串meathod的ssrs Web界面Download = bla.csv

any idea how to accomplish this? 任何想法如何做到这一点?

I had a similar scenario where my URL is redirected and then we need to download the file. 我有一个类似的场景,其中我的URL被重定向,然后我们需要下载文件。 What I did was get the redirected URL and parse for the http address and again invoked with the redirected URL. 我所做的就是获取重定向的URL并解析http地址,然后再次使用重定向的URL进行调用。 Below code worked for me. 下面的代码为我工作。

$username = "u"
$password = "p"
$auth=$username+":"+$password
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)
$latestArtifactURL = Invoke-WebRequest $url -Headers @{Authorization = "Basic $EncodedPassword"} -MaximumRedirection 0 -ErrorAction SilentlyContinue
$URLIndex = "$latestArtifactURL".IndexOf('http:')
$redirectedURL = "$latestArtifactURL".SubString("$URLIndex") 
Invoke-WebRequest $redirectedURL -Headers @{Authorization = "Basic $EncodedPassword"} -Outfile "App.zip"

You can also use the webclient to download the file. 您也可以使用webclient下载文件。 Hope this helps. 希望这可以帮助。

我认为您可以在poshcode.org上使用此脚本 ,或尝试使用System.Net.CookieContainer进行提示,以避免陷入重定向循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM