[Powershell] 利用Powershell 下載檔案

若利用Linux 的話, 可以利用wget 將檔案下載, 但在Powershell 中沒有類似的指令, 需要自己透過WebClient建立. 

$formattedCurrentDate= Get-Date -format yyMMdd
$fileName="RPF_"+$formattedCurrentDate+".zip"
$url = "http://www.hkex.com.hk/eng/market/rm/rm_dcrm/riskdata/rpf/"+$fileName
$output = "c:\iBossDayEndProcess\RPF_Files\RPF_$formattedCurrentDate.zip"

$lastExitCode=0
$start_time = Get-Date
try
{
    $wc = New-Object System.Net.WebClient
    Write-Output "Downloading file from $url"
    $wc.DownloadFile($url, $output)
    Write-Output "Download completed. Path: $output;"
}
catch
{
    Write-Output $_.Exception.Message
    Write-Output $_.Exception.ItemName
    Write-Output $_.Exception.StackTrace
    $lastExitCode=1
}
finally
{
    Write-Output "Execution completed. Duration: $((Get-Date).Subtract($start_time).Seconds) second(s)"
    exit $lastExitCode
}

最後的lastExitCode 決定其Error Level, 從而讓外間知道其執行結果. 通常0 為正常, 不是0 就是錯誤.

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.