[System.Reflection.Assembly]::LoadWithPartialName("System.web")
$docIn = "d:\temp\quickparts.docx"
$docOut = "d:\temp\quickparts-fixed.docx"
$quickparts = @{
"[Author]" = "John Doe";
"[Company]" = "Contoso";
"[Area]" = "Sales";
}
Write-Host "Start processing quickparts in $docIn"
$workDir = "$($env:TEMP)\quickparts"
if([System.IO.Directory]::Exists($workDir) -eq $false) {
New-Item -Path $workDir -ItemType Directory | out-null
} else {
Remove-Item -Path "$workDir\*" -Recurse -Force
}
Copy-Item -Path $docIn -Destination "$workDir\in.zip"
Expand-Archive -Path "$workDir\in.zip" -DestinationPath "$workDir\unzipped"
# This list of xml files to process is based where placeholders were located in my files. There may be other locations too.
$xmlFiles = @(
"$workDir\unzipped\word\header1.xml"
"$workDir\unzipped\word\header2.xml"
"$workDir\unzipped\word\header3.xml"
"$workDir\unzipped\word\glossary\document.xml"
"$workDir\unzipped\word\footer1.xml"
"$workDir\unzipped\word\footer2.xml"
"$workDir\unzipped\word\footer3.xml"
)
$anyModified = $false
foreach($file in $xmlFiles) {
Write-Host "Processing XML file: $([System.IO.Path]::GetFileName($file))..."
if([System.IO.File]::Exists($file) -eq $true) {
$file_content = [System.IO.File]::ReadAllLines( $file, [System.Text.Encoding]::UTF8 )
$modified = $false
foreach($quickpart in $quickparts.GetEnumerator()) {
$find = "<w:t>$($quickpart.Key)</w:t>" # Found by examining XML files. There may be other tags.
if([system.String]::Join(" ",$file_content).Contains($find) -eq $true) {
$replace = "$($quickpart.Value)`n"
$replace = $replace.TrimEnd("`n").Replace("`n", ", ")
$replace = [System.Web.HttpUtility]::HtmlEncode($replace)
Write-Host "`tReplaced $($quickpart.Key) in $([System.IO.Path]::GetFileName($file)) with $replace"
$replace = "<w:t>$replace</w:t>"
$file_content = $file_content.Replace($find, $replace)
$modified = $true
}
}
if($modified -eq $true) {
$anyModified = $true
[System.IO.File]::WriteAllLines( $file, $file_content, [System.Text.Encoding]::UTF8 )
}
}
}
if($anyModified -eq $true) {
Write-Host "Compress and save processed document as $docOut"
Compress-Archive -Path "$workDir\unzipped\*" -DestinationPath "$workDir\out.zip"
Copy-Item -Path "$workDir\out.zip" -Destination $docOut
} else {
Write-Host "No quick part placeholders found in $docIn"
}
Remove-Item -Path $workDir -Recurse -Force
Write-Host "Ready!"