The first version of Linux I ever used was Slackware 2.3 running one of those pesky 1.X kernels. Since then, one of my all-time favorite utilities has been the Fortune program, which displays quotes on the console when run.

fortune

I've always missed it on windows and even build (and lost) a clone of it myself once, but I'm too lazy now to try that again. Instead, this time around I simply settled for writing a simple PowerShell script that grabs a random quote from QuoteDB. It's not fancy. It has no error checking at all. It's slow (depending on your network connection and how loaded quotedb is), but alas, it works and it's fun to use.

I give you fortune.ps1:

$wc = new-object net.webclient
$js = $wc.DownloadString('http://www.quotedb.com/quote/quote.php?action=random_quote&=&=&')

function strip-html([string] $str) {
   $val = $str -replace '<[^>]+>', ''
   $val = $val -replace '`', "'"
   return $val
}

function next-word([string] $text, [int] $start) {
   $end = $start
   for ( ; $end -lt $text.Length; $end += 1 ) {
      if ( $text[$end] -eq ' ' ) {
         break
      }
   }
   return $text.Substring($start, $end - $start)
}

function wrap-text([string] $text) {
   $buf = new-object Text.StringBuilder
   $lnl = $host.UI.RawUI.WindowSize.Width - 2
   $pos = 0
   $linepos = 0
   while ( $pos -lt $text.Length ) {
      $word = (next-word $text $pos)
      if ( $linepos + $word.Length -gt $lnl ) {
         [void] $buf.Append("`n")
         $linepos = 0
      }
      [void] $buf.Append($word + ' ')
      $pos += $word.Length + 1
      $linepos += $word.Length + 1
   }
   write $buf.ToString()
}


if ( $js -ne $null ) {
   $js = $js.trim()
   $p1 = "^.+'(?.+)
'\);"

   $p2 = '">(?.+)'

   $authorline = $js.Substring($js.LastIndexOf("`n"))
   $maintext = $js.Substring(0, $js.LastIndexOf("`n"))
   if ( $maintext -match $p1 ) {
      $matches.text.Split("`n") | %{
         wrap-text (strip-html $_)
      }
   }
   if ( $authorline -match $p2 ) {
      write "`t`t-- $($matches.author)"
   }
}


Tomas Restrepo

Software developer located in Colombia.