Word-Dokumente mit Powershell generieren

Durch die integrierte COM-Anbindung ist es einfach, Applikationen wie Word und Excel über die Powershell fernzusteuern. Ausgehend von dem Beispiel auf http://command-line-programming.suite101.com/article.cfm/how_to_create_a_word_document_with_powershell, das ich etwas anpassen musste, hier ein ‚Minimalbeispiel‘:

$oWord = New-Object -Com Word.Application
$oWord.Visible = $true
 
$oMissing = [System.Reflection.Missing]::Value
$oDoc = $oWord.Documents.Add($oMissing, $oMissing, $oMissing, $oMissing)
 
# $odoc | get-Member save* |Select-Object definition| format-list
 
$oPara1 = $oDoc.Paragraphs.Add($oMissing)
 
$oPara1.Range.Style = "Überschrift 1"
$oPara1.Range.Text = "Hallo, ich bin etwas Text"
 
$oPara1.Range.InsertParagraphAfter()
$oPara1.Range.Text = "Hallo, ich bin etwas Text"
$oPara1.Range.InsertParagraphAfter()
 
$oPara2 = $oDoc.Paragraphs.Add($oMissing)
$oPara2.Range.Text = "Hier der zweite Absatz"
$oPara2.Range.InsertParagraphAfter()
 
$filename = "C:\MeinDokument.doc"
$oDoc.SaveAs([ref]$filename,[ref]$oMissing, 
[ref]$oMissing,[ref]$oMissing, [ref]$oMissing,
[ref]$oMissing,[ref]$oMissing,[ref]$oMissing, 
[ref]$oMissing,[ref]$oMissing, [ref]$oMissing,
[ref]$oMissing,[ref]$oMissing,[ref]$oMissing,
[ref]$oMissing)
 
$oDoc.Close()
$oWord.Quit()

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website