Thursday, July 18, 2013

PowerShell and RSS feeds

With google reader shutting down and with the crazy amount of rss feeds available I became curious about what an rss feed actually is.
I was amazed at how basic this whole rss feed process really is.  For instance to display the necessary xml from the latest technology news item on CBC you could run this command.
$([xml]$(New-Object System.Net.WebClient).DownloadString(“http://rss.cbc.ca/lineup/technology.xml”)).rss.channel.item[0]
This really is not formatted too nicely but it gives you the idea how easy it is to get rss feed data from online sources using powershell.

Using rss feeds I created comandlets to get a variety of information that is online. At the bottom of this post is a "Get-Weather" commandlet I added to my profile to easily display the weather forecast.

To get the weather for Houston Texas run:
Get-Weather -City Houston -Province Texas -Country US
For my current location I run:
Get-Weather

function Get-Weather {
[CmdletBinding()]
Param(  [String]$City = "Melville",
        [string]$Province = "Saskatchewan",
        [string]$Country = "Canada")
    
    if($City.Equals("Melville",[System.StringComparison]::InvariantCultureIgnoreCase) -and $Province.Equals("Saskatchewan",[System.StringComparison]::InvariantCultureIgnoreCase)) {
        $LocAbrev = "cask0200"
    }
    else {
        if($Country.Equals("US",[System.StringComparison]::InvariantCultureIgnoreCase)){$Country = "United-States"}
        [System.Reflection.Assembly]::LoadWithPartialName("System.web") | Out-Null
        $SiteUrl = “http://www.theweathernetwork.com/weather/$Country/$Province/$City”
        $Location = (New-Object System.Net.WebClient).DownloadString($SiteUrl)
        [string[]]$Test = '<script>window._uf={};window._uf.p='
        $LocAbrev = $Location.split($Test,[system.StringSplitOptions]::None)[1].split(';')[0].trim('"')
    }

    #Get The Weather From the Weather Networks RSSFeed
    [System.Reflection.Assembly]::LoadWithPartialName("System.web") | Out-Null
    $SiteUrl = “http://rss.theweathernetwork.com/weather/$LocAbrev”
    [xml]$weather = (New-Object System.Net.WebClient).DownloadString($SiteUrl)
    write-Host $weather.rss.channel.title
    foreach($Day in $weather.rss.channel.GetElementsByTagName("item")) {
       Write-Host "Date:       " $Day.title
       Write-Host "Description: " -NoNewline
       $counter = 0
       foreach($Desc in $Day.description.split(',') ) {
             if ($counter++ -ge 1) {Write-host "             " -NoNewline}
             if(![string]::IsNullOrWhiteSpace($Desc.Trim()) -and ![string]::IsNullOrEmpty($Desc.Trim())) {
                 [System.Web.HttpUtility]::HtmlDecode($Desc.Trim());
             
             }
       }
       Write-host ""
    }