Get Weather Forecast

Invoke-WebRequest can easily retrieve web page content for you. If you run it without the –UseBasicParsing parameter, the HTML is even parsed by the Internet Explorer DOM. This way, PowerShell requires just a couple lines of code to retrieve the current weather forecast for almost any city in the world:

$City = 'New York'
$weather = Invoke-WebRequest -Uri "http://wttr.in/$City" 
$text = $weather.ParsedHtml.building.outerText

$text
$text | Out-GridView

A couple of things to note:

  • Out-GridView can only display a fixed number of text lines. To see the complete report, dump $text to the console
  • Invoke-WebRequest requires that the built-in Windows browser has been run and initialized at least once
  • The code above is fragile: once the web site author decides to reorganize the page content, it may no longer work

Twitter This Tip! ReTweet this Tip!

  • @ps1 very nice tip.

    However, I can't find the property "building".

    Am I missing something?

    [13:24 PM C:\]>  $city = 'newyork'

    [13:24 PM C:\]>$weather = iwr -Uri "http://wttr.in/$city"

    [13:24 PM C:\]>  $weather.ParsedHtml | gm b*

     TypeName: mshtml.HTMLDocumentClass

    Name    MemberType Definition

    ----    ---------- ----------

    baseUrl Property   string baseUrl {get;set;}

    bgColor Property   System.Object bgColor {get;set;}

    building    Property   mshtml.IHTMLElement, Microsoft.mshtml, Version=7.