I've got a script that opens an MS Word document, then searches through a directory for each image file (.jpg), then does a find and replace using the filename as the search string, and inserts the image in place of the text it finds. My problem is that it's not doing an exact match. This means for example that if it looks for image1.jpg and that text exists in the word document inserts the image in it's place (the text being a placeholder). But if mimimage1.jpg was in place before it then it would insert the .jpg there - not doing an exact match.
Here's the code I've got so far:
# Get variables from XML file $MyDir = Split-Path $MyInvocation.MyCommand.Definition # Get settings from variables.xml. [xml]$settings = get-content "$MyDir\variables-test.xml" # Assign the settings to local variables. $SMTP = $settings.Settings.Setting.SMTP $port = $settings.Settings.Setting.port $from = $settings.Settings.Setting.EmailFrom $to = $settings.Settings.Setting.EmailTo $subject = $settings.Settings.Setting.Subject $body = $settings.Settings.Setting.Body $savepath = $settings.Settings.Setting.SavePath $docfile = $settings.Settings.Setting.WordDoc $XMLpath = "$MyDir\variables.xml" [String[]]$strXML=@() [xml]$xml = get-content $XMLpath $parse_results = New-Object System.Collections.ArrayList add-type -AssemblyName "Microsoft.Office.Interop.Word" $wdunits = "Microsoft.Office.Interop.Word.wdunits" -as [type] $application = New-Object -comobject word.application $application.visible = $false $document = $application.documents.open($docfile) set-variable -name wdGoToLine -value 3 -option constant set-variable -name wdGoToAbsolute -value 1 -option constant # Create new directory $date = (Get-Date -format "dd-MM-yyyy") $newdir = $savepath + "archive" + "-" + $date New-Item -ItemType directory -Path $newdir # Search Word document for filename and insert image foreach($file in Get-ChildItem $savepath -Filter *.jpg) { if ($application.Selection.Find.Text = $file) { if ($application.Selection.Find.Execute()) { $insertfile = $savepath + $file $objSelection = $application.selection $objShape = $objSelection.InlineShapes.AddPicture($insertfile) $gotoline = $objSelection.GoTo($wdGoToLine, $wdGoToAbsolute,1) } } } # Move spreadsheets and images to archive location and cleanup after dfm2xls.ps1 before ending script foreach($movexlsx in Get-ChildItem $savepath -Filter *.xlsx) { $xlpath = $savepath + $movexlsx Move-Item $xlpath $newdir } foreach($movejpg in Get-ChildItem $savepath -Filter *.jpg) { $imgpath = $savepath + $movejpg Move-Item $imgpath $newdir } # Save document then close application $newsave = $savepath + $date + "-report.docx" $document.SaveAs([ref]$newsave) $document.Close() $application.quit()
At the moment it doesn't do an exact match but I've tried using:
$MatchWholeWord = $True
$MatchCase = $False
and then
$application.Selection.Find.Execute($MatchWholeWord, $MatchCase)
But that stopped it from finding any matches. Can anyone help?
Thanks in advance