對Linux熟悉的讀者可能會對Linux通過wget下載文件有印象,這個工具功能很強大,在.NET環境下提到下載文件大多數人熟悉的是通過System.Net.WebClient進行下載,這個程序集能實現下載的功能,但是有缺陷,如果碰上類似于…/scripts/?dl=417這類的下載鏈接將無法正確識別文件名,下載的文件通常會被命名為dl=417這樣古怪的名字,其實對應的文件名是在訪問這個鏈接返回結果的HTTP頭中包含的。事實上微軟也提供了避免這些缺陷的程序集System.Net.HttpWebRequest 和 HttpWebResponse,本文將會使用這兩個程序集來實現PowerShell版wget的功能。
代碼不怎么復雜,基本上就是創建HttpWebRequest對象,設定UserAgent和CookieContainer以免在遇到設置防盜鏈的服務器出現無法下載的情況。然后通過HttpWebRequest對象的GetResponse()方法從http頭中獲取目標文件的大小以及文件名,以便能在下載到文件時提示當前下載進度,在下載完文件后,列出當前目錄下對應的文件。代碼不復雜,有任何疑問的讀者可以留言給我,進行交流,下面上代碼:
代碼如下:
=====文件名:Get-WebFile.ps1=====
function Get-WebFile {
<# Author:fuhj(powershell#live.cn ,http://fuhaijun.com)
Downloads a file or page from the web
.Example
Get-WebFile http://mirrors.cnnic.cn/apache/couchdb/binary/win/1.4.0/setup-couchdb-1.4.0_R16B01.exe
Downloads the latest version of this file to the current directory
#>
[CmdletBinding(DefaultParameterSetName="NoCredentials")]
param(
# The URL of the file/page to download
[Parameter(Mandatory=$true,Position=0)]
[System.Uri][Alias("Url")]$Uri # = (Read-Host "The URL to download")
,
# A Path to save the downloaded content.
[string]$FileName
,
# Leave the file unblocked instead of blocked
[Switch]$Unblocked
,
# Rather than saving the downloaded content to a file, output it.
# This is for text documents like web pages and rss feeds, and allows you to avoid temporarily caching the text in a file.
[switch]$Passthru
,
# Supresses the Write-Progress during download
[switch]$Quiet
,
# The name of a variable to store the session (cookies) in
[String]$SessionVariableName
,
# Text to include at the front of the UserAgent string
新聞熱點
疑難解答