I'm new to PowerShell but I've written the following code to read-in the filenames of whatever images are contained in the script directory and it does a find and replace on the filename. My trouble is it's not doing an exact match and when I use $MatchWholeWord it doesn't find anything. Here's the code:
# Get variable from XML file
$MyDir = Split-Path $MyInvocation.MyCommand.Definition
# Get settings from variables.xml.
[xml]$settings = get-content "$MyDir\variables.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-test.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
# For each image in directory search word document for filename and replace with image file
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 and email document then close application
$newsave = $savepath + $date + "-report.docx"
$document.SaveAs([ref]$newsave)
$document.Close()
$application.quit()
So this works, but doesn't do an exact match so if i was searching for 'shell' it would overwrite half of 'powershell'. Also using:
$MatchWholeWord = $True
$application.Selection.Find.Execute($MatchWholeWord)
doesn't match anything. Can anyone offer an alternative maybe?
Thanks in advance.