peter0816
Goto Top

Word-Dokument mit Powershell bearbeiten

Hallo,

ich würde gerne ein Worddokument, welches ich mit Variablen versehen habe, durch Werte mit Powershell ersetzten.
Hatte mir das ganze so vorgestellt:
Es existiert auf jedem Server schon eine Datei Servername.docx, die Variable in dem docx-Dokument heißt #Servername# und wird $Servername ersetzt.
$Servername = "Home1"
(Get-Content .\$Servername.docx) | Foreach-Object {$_ -replace '#Servername#', '$Servername'} | Set-Content .\$Servername.docx

Das funktioniert soweit ohne Fehlemdung, nur wenn ich das Dokument öffnen möchte, ist es leer.

Könnt ihr mir bitte helfen?

Mfg

Peter

Content-Key: 312075

Url: https://administrator.de/contentid/312075

Printed on: April 18, 2024 at 23:04 o'clock

Mitglied: 129813
129813 Aug 08, 2016 at 09:37:24 (UTC)
Goto Top
Hi
das funktioniert soweit ohne Fehlemdung, nur wenn ich das Dokument öffnen möchte, ist es leer.
This will never work!! A word document is not plain text, instead it's a binary zip-file.

You have to use COM-Automation to open the document with word and then do the replacement .

Regards
Member: Peter0816
Peter0816 Aug 08, 2016 at 09:42:20 (UTC)
Goto Top
Hallo,

wie kann ich dies dann ohne lokal installiertes Word praktizieren?

Danke

PEter
Mitglied: 129813
129813 Aug 08, 2016 updated at 09:44:57 (UTC)
Goto Top
Zitat von @Peter0816:
wie kann ich dies dann ohne lokal installiertes Word praktizieren?
If you have not installed Word, COM-Automation will not work, then you have to unzip the document, replace it in the document xml content file, replace the file in the zip and save. Much more work and prone to errors.
Member: colinardo
colinardo Aug 08, 2016 updated at 10:08:16 (UTC)
Goto Top
Hallo Peter,
über COM-Automation sieht das bspw. so aus:
$placeholder = "#SERVERNAME"  
$replacement = "ServerXYZ"  

$objWord = New-Object -Com Word.Application
$objWord.Visible = $false
$doc = $objWord.Documents.Open("C:\daten\serverxyz.docx")  
$objWord.Selection.Find.Execute($placeholder,$false,$false,$false,$false,$false,$true,1,$false,$replacement,2)
$doc.Save()
$doc.Close()
$objWord.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($objWord)
Wie man Office-Dokumente offline ohne installiertes Word bearbeiten kann kannst du in einem meiner Threads nachlesen
Pfad der Dokumentenvorlage mit einem Powershell Script ändern?

Grüße Uwe
Member: colinardo
colinardo Aug 08, 2016 updated at 11:55:52 (UTC)
Goto Top
Hier noch als Ergänzung die Replacement-Methode ohne vorhandenes Word (Variablen im Kopf):
# Benötigt wird mindestens NET-Framework 4.5 und Powershell 3.0

# Ersetzungsteile
$placeholder = "#SERVERNAME#"  
$replacement = "SERVERXYZ"  

# Datei
$filespec = "C:\daten\demo.docx"  

# benötigte Assemblies laden
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.Filesystem

gci $filespec -File | %{
    # Word-Dokument als ZIP-Datei im Update-Modus öffnen
    $zipfile = [System.IO.Compression.ZipFile]::Open($_.FullName,[System.IO.Compression.ZipArchiveMode]::Update)
    
    # Einträge der benötigte Dateien aus dem Dokument holen
    $entries = $zipfile.Entries | ?{$_.FullName -match '^(word/document\.xml|word/(header|footer)\d*\.xml)$'}   
    $remove = @()
    $entries | %{
        $tmp = "$env:TEMP\$($_.Name)"  
        # word/document.xml extrahieren
        [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$tmp)

        $content = gc $tmp
        if ($content -match [regex]::Escape($placeholder)){
            # Einträge ersetzen
            $content -replace [regex]::Escape($placeholder),$replacement | Set-Content $tmp -Encoding UTF8
            # geänderte Datei wieder hinzufügen
            [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipfile,$tmp,$_.FullName) | out-null
            $remove += $_
        }
        # Temporäre Files löschen
        del $tmp -Force -ErrorAction SilentlyContinue
    }
    # lösche ersetzte Dokumentteile im ZIP
    $remove | %{$_.Delete()}

    # Zipfile-Resourcen freigeben
    $zipfile.Dispose()
}
Falls der Beitrag gefällt, seid so nett und unterstützt mich durch eine kleine Spende / If you like my contribution please support me and donate