使用Powershell打开大型Word文档集-自动化

时间:2018-12-31 14:50:44

标签: powershell automation ms-word

我正在为具有其当前文件路径的数百个word文档分配页脚。这是我的代码,可以完成工作:

我计划将$Word.Visible设置为false,但是暂时不用于调试目的。

这会将所有单词docs放在目录中,在页脚添加文件路径,然后保存并关闭。

我正在尝试处理这样的情况:

error-window

我只想跳过此步骤,或者可能强行打开并继续。但是,不确定执行此操作的最佳方法,并且正在寻求帮助。

谢谢, 以利亚

Set-ExecutionPolicy bypass;
$path = 'somepath';

$documents = Get-ChildItem -Path $path *.docx -Recurse -Force
$filepaths = foreach ($document in $documents) {$document.fullname}
$Word = New-Object -ComObject Word.application;
$Word.Visible = $true;
foreach ($filepath in $filepaths){

    $Doc = $Word.Documents.OpenNoRepairDialog($filepath);
    $Doc.Unprotect();
    $Selection = $Word.Selection;
    $Doc.ActiveWindow.ActivePane.View.SeekView = 4;
    $Selection.ParagraphFormat.Alignment = 1;
    $Selection.TypeText($filepath);
    $Doc.Save();
    $Doc.Close();
}
$Word.Quit();

编辑1: 我进行了编辑,在其中添加了用于文件路径的动态字段对象,而不仅仅是输入文件路径,这样,如果您碰巧移动了文件,则可以将文件路径更新为新路径。在单词中选择页脚时,必须按F9键,但这是最好的选择,而无需创建宏并将文件另存为.docm。

这是修改后的代码:

$documents = Get-ChildItem -path *docx -recurse -force
$filepaths = foreach($document in $documents){$document.FullName}
Set-Variable -Name wdFieldFileName -Value 29 -Option constant -Force -ErrorAction SilentlyContinue
$word = New-Object -ComObject Word.Application
#$word.Visible = $true
foreach($filepath in $filepaths){
    $doc = $word.Documents.Open($filepath)
    $sections = $doc.Sections
    $item1 = $sections.Item(1)
    $footer = $item1.Footers.Item(1)
    $range = $footer.Range
    $doc.Fields.Add($range, $wdFieldFileName, '\p')
    $doc.Save()
    $doc.Close()
}
$word.Quit()

我试图打开已损坏的文件或通过单词诊断为“需要维修”的文件时,我仍然遇到错误窗口。 将多个参数传递给Open()方法不会产生预期的结果。这是一个示例:

Exception calling "Open" with "16" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At line:1 char:1
+ $doc = $word.Documents.Open($filepath, $False, $False, $False, $null, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

0 个答案:

没有答案
相关问题