PowerShell of the implementation of small tips file Download (class wget) _powershell

Source: Internet
Author: User
Tags couchdb webfile

Readers familiar with Linux may have an impression of Linux downloading files through wget, a powerful tool in the. Net environment Most people are familiar with downloading through the System.Net.WebClient, this assembly can achieve the function of downloading, but there is a flaw, if encounter similar to .../scripts/?dl=417 this kind of download link will not recognize the file name correctly, The downloaded file is usually named dl=417, but the corresponding file name is included in the HTTP header that accesses the result of the link. In fact, Microsoft also provides the assembly System.Net.HttpWebRequest and HttpWebResponse to avoid these defects, this article will use these two assemblies to implement PowerShell version wget function.

The code is not very complex, basically is to create a HttpWebRequest object, set the useragent and Cookiecontainer to avoid the situation when the server that set up the anti-theft chain appears unable to download. The target file size and file name are then obtained from the HTTP header by the HttpWebRequest object's GetResponse () method so that the current download progress is prompted when downloading to the file, and the corresponding file is listed under the current directory after the file is downloaded. The code is not complex, there are any questions readers can leave a message to me, to communicate, the following code:

Copy Code code as follows:

===== FileName: 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 your 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 (cookie) in
[String] $SessionVariableName
,
# Text to include at the front of the useragent string
[string] $UserAgent = "powershellwget/$ (1.0)"
)

   write-verbose "Downloading ' $Uri"
   $EAP, $ErrorActionPreference = $ Erroractionpreference, "Stop"
   $request = [System.net.httpwebrequest]::create ($Uri);
    $ErrorActionPreference = $EAP
   $request. useragent = $ (
         {0} (PowerShell {1};. NET CLR {2}; {3}; http://fuhaijun.com) "-F $UserAgent,
         $ (if ($Host. Version) {$ host.version}else{"1.0"}),
         [Environment]::version,
         [Environment]::osversion.tostring (). Replace ("Microsoft Windows", "Win")
     )

$Cookies = New-object System.Net.CookieContainer
if ($SessionVariableName) {
$Cookies = get-variable $SessionVariableName-scope 1
}
$request. Cookiecontainer = $Cookies
if ($SessionVariableName) {
Set-variable $SessionVariableName-scope 1-value $Cookies
}

try {
$res = $request. GetResponse ();
Catch [System.Net.WebException] {
Write-error $_. Exception-category resourceunavailable
Return
catch {
Write-error $_. Exception-category notimplemented
Return
}

   if (Test-path variable:res)-and $res. Statuscode-eq {
      if ($fileName-and!) ( Split-path $fileName)) {
         $fileName = Join-path (Convert-path ( Get-location-psprovider "filesystem") $fileName
     }
       ElseIf ((! $Passthru-and! $fileName)-or ($fileName-and (test-path-pathtype "Container" $fileName)))
&NBSP;&N bsp;    {
         [string] $fileName = ([Regex] ' (? i) Filename= (. *) $ '). Match ($res. headers["Content-disposition"]). GROUPS[1]. Value
         $fileName = $fileName. Trim ("\/" "")

$ofs = ""
$fileName = [Regex]::replace ($fileName, "[$] [Regex]::escape (" $ [System.io.path]::getinvalidpathchars ()] $ ([IO. Path]::altdirectoryseparatorchar) $ ([IO. Path]::D Irectoryseparatorchar)] "", "_")
$ofs = ""

if (! $fileName) {
$fileName = $res. RESPONSEURI.SEGMENTS[-1]
$fileName = $fileName. Trim ("\/")
if (! $fileName) {
$fileName = Read-host "Please provide a file name"
}
$fileName = $fileName. Trim ("\/")
if (!) ( [IO. FileInfo] $fileName). Extension) {
$fileName = $fileName + "." + $res. Contenttype.split (";") [0]. Split ("/") [1]
}
}
$fileName = Join-path (Convert-path (get-location-psprovider "filesystem")) $fileName
}
if ($Passthru) {
$encoding = [System.text.encoding]::getencoding ($res. CharacterSet)
[string] $output = ""
}

[int] $goal = $res. ContentLength
$reader = $res. GetResponseStream ()
if ($fileName) {
try {
$writer = New-object System.IO.FileStream $fileName, "Create"
catch {
Write-error $_. Exception-category Writeerror
Return
}
}
[byte[]] $buffer = new-object byte[] 4096
[int] $total = [int] $count = 0
Todo
{
$count = $reader. Read ($buffer, 0, $buffer. Length);
if ($fileName) {
$writer. Write ($buffer, 0, $count);
}
if ($Passthru) {
$output + = $encoding. GetString ($buffer, 0, $count)
} elseif (! $quiet) {
$total + + $count
if ($goal-gt 0) {
Write-progress "Downloading $Uri" "Saving $total of $goal"-id 0-percentcomplete (($total/$goal) *100)
} else {
Write-progress "Downloading $Uri" "Saving $total bytes ..."-id 0
}
}
while ($count-GT 0)

$reader. Close ()
if ($fileName) {
$writer. Flush ()
$writer. Close ()
}
if ($Passthru) {
$output
}
}
if (Test-path variable:res) {$res. Close (); }
if ($fileName) {
LS $fileName
}
}

Call the method, as follows:
Get-webfile Http://mirrors.cnnic.cn/apache/couchdb/binary/win/1.4.0/setup-couchdb-1.4.0_R16B01.exe
Download Couchdb's latest Windows Installer package here.
The execution effect is shown in the following illustration:

You can see that the current download and the total file size are displayed in the download file, and there is a progress bar showing the progress of the current download, and wget looks like a bit of a likeness. When the download is complete, you will see that the file has been downloaded.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.