从Word文档中找到的范围中提取节

时间:2018-08-08 11:31:26

标签: powershell ms-word

下面的代码工作正常,我们需要提取起点和终点,但无法获取范围。设置/选择才能正常工作

我可以从下方获取范围,只需增加一些范围并将其保存到CSV文件...

$found = $paras2.Range.SetRange($startPosition, $endPosition)-这部分无效。

$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 = $paras2.Range.SetRange($startPosition, $endPosition)

# cleanup com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

1 个答案:

答案 0 :(得分:1)

这行代码就是问题

$found = $paras2.Range.SetRange($startPosition, $endPosition)

在通过开始和结束位置指定范围时,必须相对于文档进行设置。上面的代码引用了Paragraphs集合。另外,它使用SetRange,但只能使用Range方法。所以:

$found = $doc.Range.($startPosition, $endPosition)