簡體   English   中英

文件操作:PowerShell

[英]Document manipluation: powershell

我正在嘗試處理一個大文檔,搜索“ ^ 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.

我認為我的解決方案有點愚蠢,但這是我自己的解決方案(請幫助我找到一個更好的解決方案):

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)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM