Tome's Land of IT

IT Notes from the Powertoe – Tome Tanasovski

PowerShell Mad Libs! What Else Could We Possibly Need?

Tonight I should have just taken my Nyquil and gone to bed like a good little boy.  Unfortunately, I decided to catch up on my RSS feeds.  I figured I would just read a few articles and go to bed – well I was a tad inspired by this article by Jeffrey Hicks that discusses using -f with your strings to easily throw variables into your text.  I started by making a little comment on his page -> which led to looking up mad libs websites ->which led to writing a quick script -> which led to debugging -> which led to realizing that the site had errors -> which led to error handling -> which led to more debugging -> which eventually led to this.  Well, add the above chain of events to the fact that my wife has yet to come downstairs to remind me that I’m sick and should be in bed, and you get an extremely useful script that was fun to put together, but has been even more fun to play with:

function Get-MadGlib {
<#
 .Notes
 NAME: Get-MadGlib
 AUTHOR: Tome Tanasovski
 Author's website: https://powertoe.wordpress.com
 Author's twitter: http://twitter.com/toenuff
 Version: 1.0
 CREATED: 1/19/2010
 LASTEDIT:
 1/19/2010 1.0
 Initial Release

 .Synopsis
 Gets a madlib from madglibs.com

 .Description
 Gets a madlib from madglibs.com.  If no item number is specified it gets a random madlib.
 The function asks for user input and then generates a lovely story for you.

 .Parameter ID
 The number index number of the madlib you would like to use.  If this is not specified
 it will take a random madlib.  The maximum number is currently statically set to 188.
 You cannot get any newer madlibs using the random feature - unless you modify the Get-Random
 yourself, that is.

 .Inputs
 Integer specifying the ID number of the Mad Glib you want to get.  Some Mad Glibs will not work because they are poorly formed.
 If you don't believe me go and try the page.  You will see!  They are indexed wrong or they are missing elements.  Jeeze!

 .Outputs
 String - A lovely story

 .Example
 Get-MadLib 1
  Receive a message from another world

 .Example
 Get-MadLib
  Gets a random story

 .LINK

https://powertoe.wordpress.com

#>
    param(
        [Parameter(Mandatory=$false,ValueFromPipeline=$true,Position=0)]
        [int]$ID = (Get-Random -Minimum 1 -Maximum 188)
    )
    Add-Type -AssemblyName System.Web

    $client = New-Object System.Net.WebClient

    $gliburl = "http://www.madglibs.com/printglib.php?glibid={0}" -f $ID
    $content = [System.Web.HttpUtility]::HtmlDecode($client.DownloadString($gliburl))    

    $reg = @"
(?m)^<td><img src='/images/clear.gif' alt='' width='5' height='1'></td><td align='right'>([ \S]+)<b>\[(\d+)\]</b></td><td align='left'>_+</td>$
"@
    $words = @()
    $words += ""
    $regex = [regex]$reg
    $matches = $regex.Matches($content)
    (0 .. $matches.Count) |%{$words+=""}
    $wordmatches = $matches
    $wordmatches |%{
        $words[([int]$_.groups[2].value)] = $_.groups[1].value -replace '<BR>', ''
    }
    $start = '  <i>NOTE: Some words may occur more than once.</i>([\s\S]+)<!-- =+ END GLIB FORM =+ -->'
    $content -match $start |Out-Null
    $output = $matches[1] -replace '<BR>', "`r`n"
    $output = $output -replace ' |<[\s\S]*?>', ' '
    $output = $output -replace '(?m)[ \p{Z}]+', ' ' -replace '^\s+', ''
    $output = $output -replace '\[(\d+)\]', '{$1}'
    $isgood = $true
    try {
        ("{0}" + $output) -f $words -replace '\s*[\.,]', '.' |out-null
    }
    catch [Exception] {        
        "Mad Glib #$ID is not yet supported.  Attempting another random Mad Glib"
        $isgood = $false
        Get-MadGlib
    }    
    if ($isgood) {    
        "Retrieving Input for Mad Glib #$ID"
        $wordmatches |%{
            $words[([int]$_.groups[2].value)] = Read-Host ($_.groups[1].value -replace '<BR>', '')
        }    
        ("{0}" + $output) -f $words -replace '\s*[\.,]', '.'
    }
}

So what does it mean? Sometimes I like to teach lessons with my articles, unfortunately, this one has no lesson. If you can’t make heads or tails of all of the -matches and -replace do not worry. March is Tome’s regular expression month! You should expect to see some articles from me on Hey Scripting Guy! as well as a virtual talk on 3/22 for the UK user group – wait, the talk will be real – the meeting will be virtual and accessible to all who would like to participate.

I will leave you with this doozy that was generated by Get-MadGlib -ID 15:

In the film script Wars: A New anger. Princess Scripting Wife sends out a call for help right before she gets captured by Jeffrey Snover. The call reached c x – 9 through a teenager named Luke and two turtles. Luke finds out that he is a/an IT Pro and joins up with Tome. Together they eat the princess. At the end of the film. Luke destroys the death bottle while Tome covers his puppet.

Advertisements

One response to “PowerShell Mad Libs! What Else Could We Possibly Need?

  1. Tome January 20, 2011 at 1:20 pm

    I realize that I need to add the error handling before putting you through the questions. I will fix that shortly. In the meantime, try not to get too frustrated with it 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: