Skip to content

Instantly share code, notes, and snippets.

@lkfken
Last active October 13, 2017 17:52
Show Gist options
  • Save lkfken/a4e06fad4385677d9449d9acf4a73478 to your computer and use it in GitHub Desktop.
Save lkfken/a4e06fad4385677d9449d9acf4a73478 to your computer and use it in GitHub Desktop.
Search docx files that contain the given text in a given folder
# User Inputs --------------------------------------------------------------------------------------
[cmdletBinding()]
Param(
$Path = "C:\usr\documents\msdoc"
) #end param
$findText = "find specific text"
$docs = Get-childitem -path $Path -Recurse -Include *.docx,*.doc |
where {$_.LastWriteTime -gt [datetime]"1/1/2000" -AND $_.lastwritetime -le [datetime]"12/31/2020"}
#---------------------------------------------------------------------------------------------------
# search configuration -----------------------------------------------------------------------------
$matchCase = $false
$matchWholeWord = $true
$matchWildCards = $false
$matchSoundsLike = $false
$matchAllWordForms = $false
$forward = $true
$wrap = 1
$application = New-Object -comobject word.application
$application.visible = $False
#---------------------------------------------------------------------------------------------------
$i = 1
$totalwords = 0
$totaldocs = 0
Foreach ($doc in $docs)
{
Write-Progress -Activity "Processing files" -status "Processing $($doc.FullName)" -PercentComplete ($i /($docs.Count+1) * 100)
$document = $application.documents.open($doc.FullName)
$range = $document.content
$null = $range.movestart()
$wordFound = $range.find.execute($findText,$matchCase,
$matchWholeWord,$matchWildCards,$matchSoundsLike,
$matchAllWordForms,$forward,$wrap)
if($wordFound)
{
$doc.fullname
$document.Words.count
$totaldocs ++
$totalwords += $document.Words.count
} #end if $wordFound
$document.close()
$i++
} #end foreach $doc
$application.quit()
"There are $totaldocs total guest blog articles and $($totalwords.tostring('N')) words"
#clean up stuff
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($range) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($document) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($application) | Out-Null
Remove-Variable -Name application
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment