Invoke-WebRequest pulling out quotes

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 ''
$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 ?

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. :slight_smile:
  • 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 ''

$EIN.AllElements | 
where { $_.InnerText -like '"*- Albert Einstein' } |
select -ExpandProperty Innertext |

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. :slight_smile: