創(chuàng)建Word應(yīng)用程序?qū)ο?BR>PowerShell可以通過COM接口控制Word應(yīng)用程序。有趣的地方是,雖然您可以交互式地做所有的操作,但我希望您最終能夠用腳本操作一切。我們從創(chuàng)建一個(gè)Word程序?qū)ο箝_始。
這些就是要做的所有事情。最終生成的Word文檔是可用的,雖然可能不太漂亮。在我的例子中發(fā)現(xiàn)一個(gè)問題:Word用的事非等寬字體,而PowerShell的輸出格式假設(shè)用的是等寬字體。(譯者注:可能會(huì)造成輸出的結(jié)果對(duì)不整齊)。
$objWord = New-Object -Com Word.Application
$objWord.Visible = $true
$objMissingValue = [System.Reflection.Missing]::Value
$objDocument = $objWord.Documents.Add($objMissingValue, $objMissingValue, $objMissingValue, $objMissingValue)
$objParaHeader = $objDocument.Paragraphs.Add($objMissingValue)
$objParaHeader.Range.Style = "Heading 1"
$objParaHeader.Range.Text = "The power of Microsoft Windows PowerShell"
$objParaHeader.Range.InsertParagraphAfter()
$objParaText = $objDocument.Paragraphs.Add($objMissingValue)
$objParaText.Range.Text = "I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison."
$objParaText.Range.InsertParagraphAfter()
$filename = apos;C:\\Script\\PowerShell-Example.docapos;
$objDocument.SaveAs($filename,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue)
##Once the script has added all of the required content the document should be closed:
$objDocument.Close()
$objWord.Quit()