2017年5月14日日曜日

PowerShell Word ファイル内の文字列を置換。word/document.xml

Add-Type -AssemblyName "System.IO.Compression.FileSystem";

$FilePath='C:\Users\PCUSER\Desktop\!Temp\tf00002122.docx';

$lookupTable = @{
'{Title}'='タイトル' ;
'{Heading1}'='見出し1' ;
'{Heading2}'='見出し2' ;
'{Heading3}'='見出し3' ;
'{Heading4}'='見出し4' ;
}

<#word/document.xmlを読み込み#>
$archive = [System.IO.Compression.ZipFile]::OpenRead($FilePath);
$objdocument=$archive.Entries | Where-Object{ $_.FullName -eq 'word/document.xml'};

$sr = New-Object System.IO.StreamReader($objdocument.Open(),[Text.Encoding]::GetEncoding("UTF-8"));
$DocXML=$sr.ReadToEnd();
$sr.Close();
$archive.Dispose();

 $lookupTable.GetEnumerator() | ForEach-Object {
     $NewDocXML=$NewDocXML -replace $_.Key , $_.Value;
    }

<#word/document.xmlを削除#>
$archive = [System.IO.Compression.ZipFile]::Open($FilePath,[System.IO.Compression.ZipArchiveMode]::Update);
$objdocument=$archive.Entries | Where-Object{ $_.FullName -eq 'word/document.xml'};
$objdocument.Delete();
<#word/document.xmlを追加#>
$ZipArchiveEntry=$archive.CreateEntry('word/document.xml');

$sw = New-Object System.IO.StreamWriter($ZipArchiveEntry.Open(), [Text.Encoding]::GetEncoding("UTF-8"));
$sw.Write($NewDocXML);
$sw.Close();

$archive.Dispose();

0 件のコメント:

コメントを投稿