[RedditRSS] -- Staying Classy with PS5 Part 1

Posted
Comments None

Edit 2/5: Swapped out the wall of regex in the final method with the much simpler [Net.WebUtility]::HTMLDecode() method

Without a doubt, my favorite feature of PowerShell 5 is the new, easy way to create custom classes with the ‘class’ keyword.

That’s great, Mark, but I’ve never felt the need to make a custom class before. Why should I care now?

I’m glad you asked, hypothetical reader! Custom functions (CMDlets) are a great way reuse our code in future scripts and shell work and, even more, a great way to help others do the same. Sometimes, though, the complex nature of the data that we’re working with can become cumbersome when we’re purely using custom CMDlets and creating custom objects each time. Writing custom classes can help us with these tasks, as they let us precisely define the kind of objects we’re working with, how the data is returned, and what internal processes (methods) can be run to manipulate or update the data.

First things, first, let’s load up a custom class. Execute the following in your PS5 console or ISE window.

Kind of looks like a custom function, huh? So, now how do you use it? First, find a subreddit you want to read. “https://www.reddit.com/r/PowerShell/” seems like an easy candidate. To create an object of our new class, we use the new static constructor method provided in version 5, saving the results to a variable.

$reddit = [RedditRSS]::New("https://www.reddit.com/r/PowerShell/")

Now we can view the top thread with the GetThread method

$reddit.GetThread(0) | Format-List

The number in parentheses is the index of the thread, starting with 0. Our class caches the data from the subreddit. If we want to refresh the data, we can use the Refresh method

$reddit.Refresh()

Alternately, you can also force a refresh when using the GetThread method

$reddit.GetThread(0,$true) | Format-List

This might not seem any more useful than writing a function out. Afterall, you still need to pipe the results to Format-List to read the post. Imagine, though, that you create a second class, one that is a collection of RedditRSS objects. This second class has methods to update all of them simultaneously, or search all posts for a keyword, or look for twitter posts only. In part 2, we’ll look at how you might do this, and we’ll dissect the syntax here in a little more detail to make sure you’re well equipped to start writing your own PS5 classes.

Author

Comments

There are currently no comments on this article.

Comment

Enter your comment below. Fields marked * are required. You must preview your comment before submitting it.





← Older Newer →