Friday, June 01, 2007

Spell Check in PowerShell

If you are like me, you do a lot of work in simple text editors. I'd take a sleek, versatile and fast Notepad2 over a bulky Word instance any day. So have you ever typed in a word and it looked funny? Did you spell that correctly? Well, you could open up Word and wait for it to come up and then use it's spell checker. Or, you could bring up a browser and use one of many sites that will check. My machine runs at a speed somewhere between sloth and slug. So if I don't already have one of those apps open, I'll use up my squirrel sized attention span and forget why I opened them in the first place.

I always have a PowerShell instance running. Wouldn't it be cool to test my funny looking word with a script. I'd used the NETSpell library on one of my previous projects and thought that it would be easier to access than Google's api. So what I ended up with was a good example of how to wrap a PowerShell script around an existing class library.

Here's the script:

###############################################################
###
### Spell.ps1 - Allen Mack 6/1/2007
###
### This script takes the first argument passed to it and
### runs it through the NETSpell spell checker.
###
###############################################################

[System.Reflection.Assembly]::loadfrom("c:\Program Files\NetSpell\bin\NetSpell.SpellChecker.DLL") Out-Null

$checker = New-Object NetSpell.SpellChecker.Spelling
$checker.Dictionary.DictionaryFolder = "c:\PowershellScripts"

$word = $args[0]

$result = $checker.TestWord($word)

if($result -eq $true)
{
Write-Output("`"" + $word + "`" is spelled correctly.")
}
else
{
Write-Output("`"" + $word + "`" is spelled incorrectly.")
Write-Output("Maybe you meant:")
$checker.Suggest($word)
$checker.Suggestions
}



The first thing to do is load the dll into memory. Next we create a Spelling object and point it to the directory where our dictionary lives. I copied the dictionary file to the same directory as the script. You could point it to the NETSpell installation directory. If the word is spelled correctly, I print out a message saying so. If the word is spelled incorrectly, I display the array of suggestions generated by the Spelling object.