我可以按如下方式輕松下載 Google Chrome 安裝程式:
Invoke-WebRequest "http://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile "$env:Temp\chrome_installer.exe"
但是,對于 Opera,我特別想要最新的 64 位版本。在下載頁面上https://www.opera.com/download有一個方便的鏈接:
https://download.opera.com/download/get/?partner=www&opsys=Windows&arch=x64

當我單擊“64 位”鏈接時,它會自動開始下載最新的可執行檔案,但Invoke-WebRequest在該 url 上使用不會下載檔案:
Invoke-WebRequest "https://download.opera.com/download/get/?partner=www&opsys=Windows&arch=x64" -OutFile "$env:Temp\opera_installer.exe"
我怎樣才能操縱這樣的網址:
- 像點擊下載頁面上的鏈接一樣下載檔案?
- 獲取下載的檔案的名稱(因為我看到完整的檔案版本在下載的檔案中)?
- 將該下載重定向到我選擇的目的地?
uj5u.com熱心網友回復:
要訪問安裝程式,您可以使用以下 URI:
https://get.opera.com/pub/opera/desktop/
根據您想要的版本,您可以執行以下操作:
Invoke-WebRequest "https://get.opera.com/pub/opera/desktop/92.0.4561.43/win/Opera_92.0.4561.43_Setup_x64.exe" -OutFile "$env:Temp\opera_installer.exe"
使用上面提到的鏈接,您可以執行以下操作:
#Set source URI
$uri = "https://get.opera.com/pub/opera/desktop/"
#As the links are sorted by version the last link is the newest version
(Invoke-WebRequest -uri $uri).links[-1] | %{
#Parse string to link and as we want the Windows version add 'win/', filter for 'Setup_x64\.exe$'
$uri = [Uri]::new([Uri]$uri, $_.href).AbsoluteUri 'win/'
(Invoke-WebRequest $uri).links | ?{$_.href -match 'Setup_x64\.exe$'} | %{
#Build new Uri, download file and write it to disk
$uri = [Uri]::new([Uri]$uri, $_.href)
Invoke-WebRequest -Uri $uri -OutFile "C:\tmp\$($uri.Segments[-1])"
}
}
uj5u.com熱心網友回復:
看起來您找到的下載 URL 不僅僅是一串直接重定向,而是包含一個動態構建最終目標 URL 的 JavaScript 檔案,因此Invoke-WebRequest不能與它一起使用。
但是,在Toni 的有用答案的基礎上,您可以進行一些簡單的網路抓取以確定最新版本號并從中派生下載 URL:
$VerbosePreference = 'Continue'
$downloadRootUrl = 'https://get.opera.com/pub/opera/desktop/'
$downloadTargetFile = 'Opera_Setup.exe'
# Get the version listing and match the *last* <a> element's href attribute,
# assumed to contain the latest version number.
Write-Verbose "Determining latest version via $downloadRootUrl..."
if ((Invoke-RestMethod $downloadRootUrl) -notmatch '(?s)^. <a href="([^/"] ). $') {
throw "Could not determine latest version."
}
# Extract the version number, via the automatic $Matches variable.
$latestVersion = $Matches[1]
# Construct the full download URI based on the version number.
$downloadUrl = $downloadRootUrl ('{0}/win/Opera_{0}_Setup_x64.exe' -f $latestVersion)
Write-Verbose "Downloading installer from $downloadUrl..."
& {
# Temporarily silence the progress stream, because in Windows PowerShell
# its display slows things down significantly.
$ProgressPreference = 'SilentlyContinue'
try {
Invoke-RestMethod -ErrorAction Stop -OutFile $downloadTargetFile $downloadUrl
} catch {
throw $_
}
}
Write-Verbose "Installer for version $latestVersion successfully downloaded to $downloadTargetFile."
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528432.html
標籤:电源外壳歌剧调用网络请求
