May 15
Get-Weather function for PowerShell
Since it is almost summer time in this part of the world and sunny days are precious, keeping tabs on the weather is useful. So I wrote the the following get-weather function. It uses Yahoo Weather RSS service to lookup weather for a given zipcode. The function demonstrates the XML support built into PowerShell; pretty powerful and easy to use. Since .Net provides excellent support for accessing Web Services, that support is naturally available via PowerShell as well. Another reason to move to PowerShell (if you have not already)
#get-weather function
function get-weather([int]$zipcode)
{
if($zipcode -eq 0)
{
"Usage: get-weather <U.S zipcode>";
return;
}
#Create the Service Endpoint Url
#download the rss feed and cast to xml
$webclient = new-object System.Net.WebClient
$weatherData=[xml]$webclient.DownloadString($url);
if($weatherData -ne $null)
{
$weatherData.rss.Channel.item.Title
"---------------------------------"
$weatherData.rss.Channel.item.forecast
}
}
Save the above into a script file get-weather.ps1. You would then use it as follows:
PS C:\scripts> . .\get-weather.ps1 #dot source the file
PS C:\scripts> get-weather -zip 98052
Conditions for Redmond, WA at 6:53 pm PDT
---------------------------------
day : Mon
date : 15 May 2006
low : 59
high : 85
text : Partly Cloudy
code : 29
day : Tue
date : 16 May 2006
low : 54
high : 76
text : Sunny
code : 32
The formatting is pretty basic in my case, but one can get fancy if required. A cool extension would be to display the weather in the window title or as part of the prompt. Hmm, that would be a PowerShell Gadget!