PowerShell在NuGet在進階一點的應用中,扮演蠻重要的角色。例如: 要用Scaffolding自動產生特定Model物件的對應模版時,使用NuGet Package Manager Console下指令,是非常簡便有效率的做法。許多複雜不易歸納操作方式流程的需求,要寫出好用順手且兼顧各種情境的UI頗具難度,但寫個能接受參數提供足夠彈性的功能函數,顯然簡單許多。在實務上,先有SDK、API,累積一堆應用需求後,再依常見操作情境,將複雜的API呼叫包裝成易用的操作介面,也是軟體常採用的發展策略。
這裡寫的init.ps1只是個空殼,由NuGet Package Manager接入$installPath, $toolsPath, $package三個參數,接著用$toolsPath找到"GoogleWeather.psm1"這個PowerShell Module並載入。
param($installPath, $toolsPath, $package)
Import-Module (Join-Path $toolsPath GoogleWeather.psm1)
Register-TabExpansion "Get-Weather" @{
'city' = { "台北市", "台中市", "高雄市" }
#由XML節點取出data Attribute的小函數
function GetData($node, [string]$name)
$data = $node.SelectSingleNode($name)
return $data.GetAttribute("data")
function Get-Weather($city) {
$wc = New-Object System.Net.WebClient
$url = "http://www.google.com/ig/api?hl=zh-TW&weather=" + $city
$result = $wc.DownloadString($url)
$xml = ([Xml]$result).xml_api_reply
$info = $xml.weather.forecast_information
$display = "=== " + $(GetData $info "forecast_date")
$display += " " + $(GetData $info "city") + "氣象資訊 ============`n"
$curr = $xml.weather.current_conditions
$display += "現在天氣:" + $(GetData $curr "condition") + "`n"
$display += "氣溫:" + $(GetData $curr "temp_c") + " "
$display += $(GetData $curr "humidity") + "`n"
$wind = GetData $curr "wind_condition"
if ($wind -ne "N/A") { $display += $wind + "`n" }
$display += "============================================`n"
$xml.weather.SelectNodes("//forecast_conditions") | ForEach-Object {
$display += $(GetData $_ "day_of_week") + " "
$display += $(GetData $_ "low") + " - " + $(GetData $_ "high")
$display += " / " + $(GetData $_ "condition") + "`n"
#註冊Get-Weather,以便在NuGet Console中呼叫
Export-ModuleMember Get-Weather
(這... 真的會有人一邊寫程式一邊關心氣象嗎? 好吧! 我承認它只是我用來練習寫NuGet命令模組的自嗨作品,嚴禁任何人討論它的實用價值,呵!)