Friday Fun: Read Me a Story

announcer A few days ago, someone on Twitter humorously lamented the fact that I expected them to actually read a blog post. After the laughter subsided I thought, well why does he have to? Perhaps I can make it easier for him. Plus I needed something fun for today. So I put together a PowerShell function I call Invoke-BlogReader which I think you’ll have fun playing with. It isn’t 100% perfect and as with most Friday Fun posts, serves more as an educational device than anything.

The function uses the .NET System.Speech class which seems to be a bit easier to use than legacy COM alternative. Here’s a snippet you can test.

So basically, all I have to do is get the contents of a blog article and pass the text to the voice object. That is a bit easier said than done which you’ll see as you look through this code.

The function uses the Invoke-WebRequest cmdlet to retrieve the content from the specified web page and I then parse the HTML looking for the content.

This is the trickiest part because different blogs and sites use different tags and classes. There is a getElementsbyClassName method, but that seems to be hit and miss for me, so I’ve opted for the slower but consistent process of using Where-Object.

Once I have the content, I could simply pass the text, but I realized I may not want to listen to the entire post. Especially for my own which often have script samples. Those aren’t very pleasant to listen to. So I realized I needed to parse the content into sentences. Regular expressions to the rescue.

Don’t ask me to explain the regex pattern. I “found” it and it works. That’s all that matters. $Sentences is an array of regex match objects. All I need to do is pass the value from each match to the voice object. The other benefit is that I can include a parameter to also display the text as it is being read.

That’s all there is to it! If you want to try out all of the options here’s a sample command:

Where this can get really fun is using another function, which I’m not sure I ever posted here, to get items from an RSS feed.

Putting it all together you can get the feed, pipe it to Out-Gridview, select one and have the blog read to you!

So now you can have your blog and listen to! There are probably a number of ways this could be enhanced. Or perhaps you want to take some of these concepts and techniques in another direction. If so, I hope you’ll let me know where you end up. Have a great weekend.