howto save my word document as


I have this code and it will find in this example the word FedEx in the word documents under the C:\temp folder and puts this in a csv file.
now I want to save the file with $findtext + “_” original filename.
original filename is “shipping arrangements.docx” and I want it to be saved as(if the word Fedex is found anywhere within the doc) Fedex_shipping arrangements.docx

Here is the code
Set-StrictMode -Version latest
$path = “c:\Temp”
$files = Get-Childitem $path -Include .docx,.doc -Recurse | Where-Object { !($_.psiscontainer) }
$output = “c:\temp\wordfiletry.csv”
$application = New-Object -comobject word.application
$application.visible = $False
$findtext = “FEdEx”
$charactersAround = 0
$results = @{}

Function getStringMatch

Loop through all *.doc files in the $path directory

Foreach ($file In $files)
$document = $$file.FullName,$false,$true)
$range = $document.content

If($range.Text -match “.{$($charactersAround)}$($findtext).{$($charactersAround)}”){
$properties = @{
File = $file.FullName
Match = $findtext
TextAround = $Matches[0]
$results += New-Object -TypeName PsCustomObject -Property $properties

$results | Export-Csv $output -NoTypeInformation



import-csv $output

if there is one word doc it will work with 2 word documents in there I get this error
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named ‘op_Addition’.
At line:26 char:14

  • … $results += New-Object -TypeName PsCustomObject -Property …
  • CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
  • FullyQualifiedErrorId : MethodNotFound

any pointers?

You’re posting this question again? If this script will work fine for one document, then the following changes should solve your problem.

Change these 2 lines

$results = @{}

$results += New-Object -TypeName PsCustomObject -Property $properties

to these

$results = @()

$results += (New-Object -TypeName PsCustomObject -Property $properties)

The issue is you made $results a hashtable and you need to enclose the new-object command in parenthesis to make a subexpression.