- Dwarfsoft [GPA] - http://www.dwarfsoft.com/blog -

Word.Application Trolling in PowerShell

I’ve been doing a little bit of investigation into OneNote and Word in PowerShell. So after this I got around to thinking of some of the mischievous things that could be achieved with some of the things I’ve learned… Like enumerating all documents, and in those documents enumerating all sentences, and then providing a 1% opportunity to replace its Font with Wingdings.

The following script demonstrates managing multiple threads, and managing the closure of those threads/jobs once they are complete. I’ve tested this on my C:\Temp folder with a number of documents in it, and the results are as expected. It provides some amusing opportunities for trolling.

$docroot = "C:\Temp"
$factor = 0.99
$max = 1000
$maxprocess = 20
$evilblock = {
  Param($FilePath,$Max,$Factor)
  $word = new-object -ComObject "word.application"
  $doc = $word.Documents.Open($FilePath, $False) 
  $doc.Sentences | %{ 
    if ((Get-Random -Maximum $max) -ge ($max*$factor))
    {
      $_.Font.Name = "Wingdings"
    }
  }
  $doc.Save()
  $doc.Close()
  $word.Quit()
}

gci $docroot -filter *.doc* -Recurse | %{
  While ((Get-job -State Running).Count -ge $maxprocess)
  {
    Sleep -Seconds 2
  }
  Get-job -State Completed | Remove-Job
  Start-Job -ScriptBlock $evilblock -ArgumentList $_.FullName,$max,$factor
} 

Cheers, Chris.