powershell操作word
我假設許多讀者用PowerShell生成服務器、事件以及Windows網絡上各種數據的報表。您也許創(chuàng)建過純文本文件,甚至漂亮的HTML報表。但是您也可以用上Microsoft Word,當然,前提是您已經安裝了Word。在這個系列的第二部分,我將會向您演示如何用PowerShell為Word文檔套用樣式。
創(chuàng)建Word應用程序對象
PowerShell可以通過COM接口控制Word應用程序。有趣的地方是,雖然您可以交互式地做所有的操作,但我希望您最終能夠用腳本操作一切。我們從創(chuàng)建一個Word程序對象開始。
下一步,我們創(chuàng)建一個文檔對象。
這些就是要做的所有事情。最終生成的Word文檔是可用的,雖然可能不太漂亮。在我的例子中發(fā)現一個問題:Word用的事非等寬字體,而PowerShell的輸出格式假設用的是等寬字體。(譯者注:可能會造成輸出的結果對不整齊)。
第二個示例
$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 = 'C://Script//PowerShell-Example.doc'
$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()
新聞熱點
疑難解答
圖片精選