Invoke-WebRequest pulling out quotes

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Graham Beer Graham Beer 9 months ago.

  • Author
    Posts
  • #36244
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Had this idea to get an Albert Einstein quote every time I open Powershell, for a bit of fun. So digging around I found a site with lots of Einstein quotes created this little script:

    $EIN = Invoke-WebRequest -Uri 'http://www.alberteinsteinsite.com/quotes/einsteinquotes.html'
    $EIN.AllElements |  where {$_.innerhtml -like "`"*" } | Sort-Object { $_.InnerHtml.Length } |
    where{$_.InnerText -match "- Albert Einstein*"} | select -ExpandProperty Innertext | sort{get-random} | select -First 1
    

    It works like a treat. But I would like to know have I approached this in the right way and is my usage of powershell right ?

  • #36248
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    It'll be easier once they add the RSS feed option (which is meant to be consumed easily by computers), but you're off to a good start. My observations:

    – You've got two calls to Sort-Object, and I'm not sure why either one needs to be there. (More on this a bit later).
    – You've got two calls to Where-Object, which could be combined into one, if you like.
    – You're using the match operator with something that looks more like a -like wildcard pattern than a regular expression. (-match uses regex.)
    – You're using | sort{get-random} | select -First 1. You can just pipe objects to Get-Random and it'll pick one for you, no need for the "sort and select" approach. 🙂
    – You're using double-quoted strings, and then you need to escape your double quotation mark inside the string. Since you don't need to expand anything, you could just use a single-quoted string, which would eliminate the need to escape the double quote.

    Here's a tweak of your code that takes those observations into account. It should do exactly the same thing, but the code feels a little cleaner to me:

    $EIN = Invoke-WebRequest -Uri 'http://www.alberteinsteinsite.com/quotes/einsteinquotes.html'
    
    $EIN.AllElements | 
    where { $_.InnerText -like '"*- Albert Einstein' } |
    select -ExpandProperty Innertext |
    Get-Random
    
  • #36249
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Hi Dave, thanks. Your code is a lot cleaner. You've stripped away so much of mine, which looks far to messy/complicated. Scary how simple and effective yours is. 🙂

You must be logged in to reply to this topic.