我覺得我的解決方案是有點兒傻,但這裏是我自己的解決方案(請幫我找到一個更好的):
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)
}
}
}
無論是VBScript還是PowerShell,您仍在使用Word對象模型,使用相同的方法。如果您可以在VBScript中「執行readline並將其保存到緩衝區」,它應該在PowerShell中幾乎相同(語法除外) - 除非您指的是讀取純文本文件而不是Word文檔。我沒有以這種方式使用Word,但是快速搜索表明您可能想要使用[選擇對象](http://msdn.microsoft.com/en-us/library/office/aa223084(v = office)。 11).aspx)和'Selection.MoveEndUntil('^ m')'來設置端點(不確定起點)。 – alroc
如果這是vbscript,我只會打開一個文本文件,但powershell讓我使用com對象。 – Jeff
我不知道VBScript可以像閱讀文本一樣閱讀Word文檔。你是在談論Word中的VBScript,還是從Windows Script Host(這就是我指的)? – alroc