這些就是要做的所有事情。最終生成的Word文檔是可用的,雖然可能不太漂亮。在我的例子中發現一個問題:Word用的事非等寬字體,而PowerShell的輸出格式假設用的是等寬字體。(譯者注:可能會造成輸出的結果對不整齊)。
$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()