2009-06-23

Powershell Scripting Games - Day 7

Here is my solution for the Beginner Event 7

Here we had to create a logging solution for script

   1: # ------------------------------------------------------------------------
   2: # NAME: ReplaceWordInWord.ps1
   3: # ------------------------------------------------------------------------
   4:  
   5: $mypath = "c:\temp\test.doc"
   6: $logfile = "c:\temp\logfile.txt"
   7: #first we will see if the logfile exists
   8: $exists = Test-Path c:\temp\logfile.txt
   9:     
  10:     if ($exists -eq $true) {
  11:         Remove-Item C:\temp\logfile.txt
  12:         }
  13:     New-Item -path c:\temp\ -Name logfile.txt -type "file" #Create the logfile
  14:  
  15: "$(get-date) -- Created Log file: $logfile" | Out-File ` 
  16:     -Encoding ascii -Append $logfile
  17:  
  18: $objWord = New-Object -ComObject word.application
  19: $objWord.Visible = $True
  20: "$(get-date) -- We have launched word" | Out-File ` 
  21:     -Encoding ascii -Append $logfile
  22:  
  23: $objDoc = $objWord.Documents.Open($mypath)
  24: "$(get-date) -- We have the document" | Out-File ` 
  25:     -Encoding ascii -Append $logfile
  26:  
  27: $objSelection = $objWord.Selection
  28: $FindText = "mispelled"
  29: $ReplaceText = "spelled incorrectly"
  30: "$(get-date) -- Replacing '$FindText' with '$ReplaceText'" | Out-File ` 
  31:     -Encoding ascii -Append $logfile
  32:  
  33: $ReplaceAll = 2
  34: $FindContinue = 1
  35: $MatchCase = $False
  36: $MatchWholeWord = $True
  37: $MatchWildcards = $False
  38: $MatchSoundsLike = $False
  39: $MatchAllWordForms = $False
  40: $Forward = $True
  41: $Wrap = $FindContinue
  42: $Format = $False
  43:  
  44: "$(get-date) -- Executing command" | Out-File -Encoding ascii -Append $logfile
  45:  
  46: $objSelection.Find.Execute($FindText,$MatchCase,
  47:   $MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
  48:   $MatchAllWordForms,$Forward,$Wrap,$Format,
  49:   $ReplaceText,$ReplaceAll)
  50:  
  51: "$(get-date) -- Replace text complete" | Out-File ` 
  52:     -Encoding ascii -Append $logfile