文档操作:powershell

时间:2012-12-03 17:35:08

标签: powershell vbscript ms-word

我正在尝试获取一个大文档,搜索“^ m”(分页符)并为我找到的每个分页符创建一个新的文本文件。

使用:

$SearchText = "^m"
$word = new-object -ComObject "word.application"
$path = "C:\Users\me\Documents\Test.doc"
$doc = $word.documents.open("$path")
$doc.content.find.execute("$SearchText")

我能够找到文本,但如何在分页之前将文本保存到新文件中?在VBScript中,我只是做一个readline并将其保存到缓冲区,但PowerShell有很大的不同。

编辑:

$text = $word.Selection.MoveUntil (cset:="^m")

返回错误:

Missing ')' in method call.

1 个答案:

答案 0 :(得分:0)

我认为我的解决方案有点愚蠢,但这是我自己的解决方案(请帮我找一个更好的解决方案):

Param(
[string]$file
)
#$file = "C:\scripts\docSplit\test.docx"

$word = New-Object -ComObject "word.application"
$doc=$word.documents.open($file)
$txtPageBreak = "<!--PAGE BREAK--!>"
$fileInfo = Get-ChildItem $file
$folder = $fileInfo.directoryName
$fileName = $fileInfo.name
$newFileName = $fileName.replace(".", "")

#$findtext = "^m"
#$replaceText = $txtPageBreak

function Replace-Word ([string]$Document,[string]$FindText,[string]$ReplaceText) {

    #Variables used to Match And Replace

    $ReplaceAll = 2
    $FindContinue = 1

    $MatchCase = $False
    $MatchWholeWord = $True
    $MatchWildcards = $False
    $MatchSoundsLike = $False
    $MatchAllWordForms = $False
    $Forward = $True
    $Wrap = $FindContinue
    $Format = $False

    $Selection = $Word.Selection

    $Selection.Find.Execute(
        $FindText,
        $MatchCase,
        $MatchWholeWord,
        $MatchWildcards,
        $MatchSoundsLike,
        $MatchAllWordForms,
        $Forward,
        $Wrap,
        $Format,
        $ReplaceText,
        $ReplaceAll
    )

    $newFileName = "$folder\$newFileName.txt"
    $Doc.saveAs([ref]"$newFileName",[ref]2)
    $doc.close()
}



Replace-Word($file, "^m", $txtPageBreak)



$word.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
Remove-Variable word


#begin txt file manipulation

#add end of file marker
$eof = "`n<!--END OF FILE!-->"
Add-Content $newfileName $eof

$masterTextFile = Get-Content $newFileName
$buffer = ""
foreach($line in $masterTextFile){
    if($line.compareto($eof) -eq 0){
        #end of file, save buffer to new file, be done
    }
    else {
        $found = $line.CompareTo($txtPageBreak)

        if ($found -eq 1) {
            $buffer = "$buffer $line `n"
        }

        else {
            #save the buffer to a new file (still have to write this part)
        }
    }
}