Awhile ago I posted an article demonstrating using Invoke-Webrequest which is part of PowerShell 3.0. I used the page at Manning.com to display the Print and MEAP bestsellers. By the way, thanks to all of you who keep making PowerShell books popular. My original script simply wrote the results to the screen. But I decided I wanted a way for my books to stand out so I made a slight adjustment.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
#requires -version 3.0 #this version will color code titles that contain the key word #it must be run in the PowerShell console Param( [ValidateNotNullorEmpty()] [string]$Keyword="PowerShell", [ValidateScript({[enum]::GetNames([consolecolor]) -contains $_})] [string]$Color="Green" ) #the web address to retrieve $url= "http://manning.com" #this is a one-time request $data = Invoke-Webrequest -Uri $url -DisableKeepAlive <# the print best sellers will be listed first MEAP best sellers willbe second $data.ParsedHtml.getElementsByTagName("div") | Where "classname" -eq "bestsellBox" | Select -First 1 -ExpandProperty InnerText #> #parse out the DIV tags looking for bestSellbox $text = $data.ParsedHtml.getElementsByTagName("div") | Where "classname" -match "^bestsell" | Select -ExpandProperty InnerText foreach ($element in $text) { #parse the text $element.split("`n") | foreach { #write titles with keyword in the name in Green #won't work in the ISE if ($_.trim() -match $keyword ) { $c = $color } else { #use the current console color $c = $host.ui.RawUI.ForegroundColor } #display the result Write-Host $_ -ForegroundColor $c } #insert a blank line between Print and MEAP bestsellers write "`r" }
The script still uses Invoke-Webrequest to parse out the page from Manning.com. But I added some logic to check each title for a keyword, like PowerShell. If found, I define a color variable and display the result using Write-Host and that color. If it isn't found, the color is set to the current foreground color. This script will only work in the PowerShell console.
Now before anyone starts yelling about using Write-Host, yes I realize all I'm doing is writing to the screen. But in this situation I am fine with that. I will never have a need to do anything else other thank read the information and adding some color to it make it even easier.
However, I did add some flexibility by adding parameters to specify the key word and color. I set some defaults and included parameter validation. Here's the default result:
But I can just as easily check for other values.
Obviously this script is really only useful to me or other Manning authors curious about where our books stand. But this is a Friday Fun article so I hope you picked up a useful tip or trick.
5 thoughts on “Friday Fun Color My Web”
Comments are closed.