首页 > 解决方案 > 为什么在 word 文件中更新日期和版本不起作用

问题描述

在我的项目中,我有以下代码可以在 word 文档中查找和替换版本号和日期,但由于某种原因它不起作用。我可以从你们那里得到帮助以了解它为什么不起作用吗?这是我在 Jenkins + MSBuild 中使用的 ps1 文件。谢谢

<#
Uses Microsoft Word automation to substitute Version and ReleaseDate values, and yield a PDF.
#>
function UpdateDocumentation {
    param (
        [string] $Path,
        [string] $Version,
        [string] $ReleaseDate
    )
    
    $path = Resolve-Path -Path $Path;

    $word = New-Object -ComObject Word.Application;
    $doc = $word.Documents.Open($path);
    $selection = $word.Selection
    $Forward = $MatchWholeWord = $true;
    $Format = $MatchAllWordForms = $MatchCase = $MatchSoundsLike = $MatchWildcards = $Wrap = $false;

    $FindText = "%Version%";
    $ReplaceWith = [System.Version]::Parse($Version).ToString(3);

    $selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format,
            $ReplaceWith, [Microsoft.Office.Interop.Word.WdReplace]::wdReplaceAll);

    $FindText = "%ReleaseDate%";
    $ReplaceWith = [DateTime]::Today.ToString("MMMM yyyy");

    $selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format,
            $ReplaceWith, [Microsoft.Office.Interop.Word.WdReplace]::wdReplaceAll);
        
    $pdf = [System.IO.Path]::ChangeExtension($(Resolve-Path $Path), '.pdf');

    $doc.SaveAs($pdf, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatPDF);
    $doc.Close([Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges);
    $word.Quit();
}

以及对它的调用:

UpdateDocumentation -Path '.\assureid-documentation\assureid-word-pdf-docs\assureid-sentinel\AssureID Sentinel Deployment Guide.docx' `
        -Version $Version -ReleaseDate [DateTime]::Today

该文档包含以下文本:版本 %VERSION% %RELEASEDATE%

标签: jenkinsms-wordmsbuild

解决方案


我对一些 Excel 方法也有类似的问题。您是否可以尝试不定义不需要使用的可选参数:

$selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $null, $null, $null, $null, $null, $null,
        $ReplaceWith, [Microsoft.Office.Interop.Word.WdReplace]::wdReplaceAll);

推荐阅读