Powershell - Extract sections from range found in word document RRS feed

  • Question

  • Below code works fine, we got start and end point which needs to be extracted but im not able to get range.set/select to work

    I'm able to get the range from below, just need to extra and save it to csv file...

    $found= $doc.Range($startPosition, $endPosition).Select() - this piece doesnt work...

        $file = "D:\Files\Scan.doc"
        $SearchKeyword1 =  'Keyword1'
        $SearchKeyword2 =  'Keyword2'    
        $word = New-Object -ComObject Word.Application
        $word.Visible = $false
        $doc = $word.Documents.Open($file,$false,$true)
        $sel = $word.Selection
        $paras = $doc.Paragraphs
        $paras1 = $doc.Paragraphs
        $paras2 = $doc.Paragraphs
        foreach ($para in $paras)
            if ($para.Range.Text -match $SearchKeyword1)
                write-host $para.Range.Text
                $startPosition = $para.Range.Start
        foreach ($para in $paras1)
            if ($para.Range.Text -match $SearchKeyword2)
                write-host $para.Range.Text
                $endPosition = $para.Range.Start
        Write-host $startPosition
        Write-host $endPosition
    $found= $doc.Range($startPosition, $endPosition).Select()
    $found.Text | Out-File "D:\Found.txt"
        # cleanup com objects
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
    Wednesday, August 8, 2018 11:47 AM

All replies

  • Hi Lokesh,

    Thanks for your question.

    After I run your script, I got the result as you. When I tried to delete ".select()", it got the result you wanted.

    So you can try to change you script.

    $found= $doc.Range($startPosition, $endPosition)
    $found | Out-File "D:\test\Found2.txt" -Force

    If you want to save it to CSV file, you can change the extension to .csv file.

    I found the link about the word paragraph range and selection object below.

    click it

    Best Regards,


    Just do it.

    Tuesday, August 14, 2018 7:48 AM