HTTPダウンロードするには を関数にしてみました。
使用方法は
HTTPダウンロードする。この場合はカレントディレクトリに保存されます。
Download-File "http://hiro.wankuma.com/index.html"
保存先ディレクトリを指定してダウンロードする
PS > Download-File "http://hiro.wankuma.com/index.html" "c:\Work"
保存先ディレクトリに名前を付けてダウンロードする
PS > Download-File "http://hiro.wankuma.com/index.html" "C:\Work" "sample1.html"
ヘルプを表示するする
PS > Download-File /?
Download-File.ps1
#===============================================================================
# Download-File: 指定されたリモート ファイルをダウンロードする
# Param:
# $url : ダウンロードするファイルURL
# $SaveDir : 保存先ディレクトリ(省略した場合はカレントディレクトリ)
# $filename : 保存ファイル名(省略した場合はダウンロードしたファイル名となる)
#
# ヘルプを見る場合は
# Download-File /?
#
# copyright HIRO's.NET(http://hiro.wankuma.com/)
#===============================================================================
function global:Download-File
{
Param ([string]$url, [string]$SaveDir, [string]$filename)
#ヘルプの参照か?
if ( $url -eq "/?" )
{
$helpmsg = @"
書式`r`n
Download-File [`$url] [[`$SaveDir]] [[`$filebame]]`r`n
パラメータ`r`n
`$url
ダウンロードするファイルURL`r`n
`$SaveDir
ダウンロードしたファイルを保存するディレクトリ
省略した場合はカレントディレクトリに保存します`r`n
`$filename
保存ファイル名
省略した場合はダウンロードしたフィル名となります`r`n
`r`n
使用例`r`n
# http://hiro.wankuma.com/index.html をダウンロードする
# この場合はカレントディレクトリに index.html というファイル名で保存される
Download-File "http://hiro.wankuma.com/index.html"
#指定したディレクトリに保存する
Download-File "http://hiro.wankuma.com/index.html" "C:\Work"
#指定したディレクトリに名前を付けて保存する
#この場合は C:\Work に sample1.html という名前で保存する
Download-File "http://hiro.wankuma.com/index.html" "C:\Work" "sample1.html"
#ヘルプを参照する
Get-DateFileName /?
"@
Write-Host $helpmsg
return
}
$webClient = new-object System.Net.WebClient
#保存先が指定されていない場合
if ( $SaveDir.Length -eq 0 )
{
#カレントディレクトリを保存先にする
$SaveDir = $(get-location).Path
}
#保存ファイル名が指定されていない場合
if ( $filename.Length -eq 0 )
{
#指定されたURLからファイル名を取得
$uri = new-object Uri($url)
$filename = $uri.Segments[$uri.Segments.Length-1]
}
if ( $filename -eq "/" )
{
Write-Host "ダウンロードできません。`r`nURLはファイル名を含めて指定してください!!" -foregroundcolor red
return
}
#保存先パス文字列の作成
$filePath = [System.IO.Path]::Combine($SaveDir, $filename)
#ダウンロードする
$webClient.DownloadFile($url,$filePath)
}