Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Count Occurrences of Specific String in Word Documents

$
0
0

I would like to preface this entire post with a clear disclaimer: I have no idea what I'm doing. I've donevery minimal PowerShell before, would like to learn more, but have no idea how to go about it. To try and help myself, I'm attempting to help a friend with some paper grading by writing a script that will output the number of periods in a document, whether .docx or .txt. I have it working just fine for plain .txt, but really have no clue whatsoever what I'm doing regarding using Word like this.

Below is my current progress, where you can see my latest, more-or-less random, very embarrassing attempt to get this working. I would appreciate anyone who's willing to have mercy and at least point me in the right direction.

$folder = Read-Host -Prompt 'Input your folder (example: C:\Folder) with the files you want graded'
$txtlist = Get-ChildItem $folder | Where-Object {$_.Name -match '.txt'}

foreach ($txt in $txtlist)
{
    $txtCount = (Get-Content $folder\$txt | Select-String -Pattern "." -AllMatches).matches.count
    Write-Host "$txt has $txtCount periods."
}

$doclist = Get-ChildItem $folder | Where-Object {$_.Name -match '.docx'}
$word = New-Object -ComObject Word.Application
$Word.Visible = $False

foreach ($doc in $doclist)
{
    $docCount = ($word.Documents.Open($doc.FullName).Find.Execute('.')).matches.count
    Write-Host "$doc has $docCount periods."
    $word.Application.ActiveDocument.Close()
}


Viewing all articles
Browse latest Browse all 21975

Trending Articles