下载文件的脚本
下午在http://www.peterprovost.org/
看到一个post,是一个download file的script
$webclient = new-object System.Net.WebClient
$start = $args[0].LastIndexOf("/") + 1
$len = $args[0].LastIndexOf("?") - $start
if( $len -lt 0 ) { $len = $args[0].Length - $start }
$target = [System.IO.Path]::Combine( $(get-location), $args[0].Substring( $start, $len ) )
$webclient.DownloadFile($args[0], $target)
$start = $args[0].LastIndexOf("/") + 1
$len = $args[0].LastIndexOf("?") - $start
if( $len -lt 0 ) { $len = $args[0].Length - $start }
$target = [System.IO.Path]::Combine( $(get-location), $args[0].Substring( $start, $len ) )
$webclient.DownloadFile($args[0], $target)
看完觉得有点别扭,因为URI 和URIBUILDER类已经提供了许多方法和属性来解析URI,没必要太多借助于String的方法,试着改了一下
Param ( [Uri]$Uri , [String]$LocalFile, [switch]$OverWrite )
# $Uri cannot be NULL
if (!$Uri) {
Write-Host "Usage: $($MyInvocation.InvocationName) Uri file [-OverWrite]";
Exit
}
#parse the uri
$Seg = $Uri.segments
if (!$Seg -or ($Seg.Count -le 1)){
Write-Host "Invalid Uri";
Exit
}
#if the end of the uri is '/', it should not be a file
$File = $Seg[$Seg.Count - 1]
If ($File.EndsWith("/")) {
Write-Host "Maybe Not A File";
Exit
}
If (! $LocalFile) {
$LocalFile = $File
}
#If file exist and no OverWrite switch,exit
if ( (test-path $LocalFile) -and (! $OverWrite) ) { "File '$LocalFile' exists, exiting"; exit }
#start download
Write-Host "Downloading"
$webclient = new-object System.Net.WebClient
$webclient.DownloadFile($Uri, $LocalFile)
Usage: ./Script.msh www.xxx.com/xxx.xxx file [-o]# $Uri cannot be NULL
if (!$Uri) {
Write-Host "Usage: $($MyInvocation.InvocationName) Uri file [-OverWrite]";
Exit
}
#parse the uri
$Seg = $Uri.segments
if (!$Seg -or ($Seg.Count -le 1)){
Write-Host "Invalid Uri";
Exit
}
#if the end of the uri is '/', it should not be a file
$File = $Seg[$Seg.Count - 1]
If ($File.EndsWith("/")) {
Write-Host "Maybe Not A File";
Exit
}
If (! $LocalFile) {
$LocalFile = $File
}
#If file exist and no OverWrite switch,exit
if ( (test-path $LocalFile) -and (! $OverWrite) ) { "File '$LocalFile' exists, exiting"; exit }
#start download
Write-Host "Downloading"
$webclient = new-object System.Net.WebClient
$webclient.DownloadFile($Uri, $LocalFile)
Ps:其实借助.net的能力,实现断电续传和多线程都是可能的,只不过如果太复杂,脚本就不适合了,C#和VB更合适。