powershell - 在PowerShell中的Word文档文件的不同页面上的不同标题?

标签 powershell ms-word powershell-2.0

我在读取多个文本文件并尝试添加后创建了一个doc文件
Powershell 中文档文件中对应页面标题的文本文件名
但是下面的代码将最后读取的文件写为每页的标题。
注意:-数据显示在doc文件上正确,只有 header 未正确写入。
如何将文本文件名写为doc的 header (意味着同一doc在不同页面上将具有不同的 header )

$dir="D:\abcd"
$val=ls $dir
$file_count=(get-childitem .).count
$page_count=0
$hash=@{};
set-variable -name wdAlignPageNumberCenter -value 1 
$Word = New-Object -ComObject Word.Application
$Word.Visible = $true
$Doc = $Word.Documents.Add()
$Section = $Doc.Sections.Item(1)
$Header = $Section.Headers.Item(1)
$Footer = $Section.Footers.Item(1)
$Footer.PageNumbers.Add($wdAlignPageNumberCenter)
$selection=$word.Selection
$page="`tPage";
$loop=1
foreach ($file in $val){
    $filename = "D:\abcd\$file"
    $filedata = (get-content $filename);
    $Footer.Range.Text=$page
    $head="ABCD`t`tFile ID: $file"
    $Header.Range.Text = $head  
}
$savepath="D:\abcd\$file.docx"
$Doc.SaveAs([ref]$savepath) 
$Doc.Close()

最佳答案

在Word中,可以通过section拆分文档的不同部分来创建唯一的标题。您遇到的问题是因为似乎只有一个部分,所以也将只有一个 header ...在foreach循环中被覆盖了。此行为与您描述的结果一致,因为最后读取的文件将作为整个文档的标题出现,这才有意义。

您已经在此处指定了一个部分(和一组页眉/页脚):

$Section = $Doc.Sections.Item(1)
$Header = $Section.Headers.Item(1)
$Footer = $Section.Footers.Item(1)

每次需要不同的标题时,只需修改逻辑以创建一个新的逻辑即可。

关于powershell - 在PowerShell中的Word文档文件的不同页面上的不同标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18981319/

相关文章:

powershell - 根据修改时间删除目录

vba - 用VBA提取Word文档目录的标题和页码

来自高级 (cmdlet) 功能的 PowerShell Add-PSSnapIn

powershell - 有没有更好的方法在没有空格的字符串中连接变量?

powershell - 获取远程注册表值

Powershell Active Directory - 将我的 get-aduser 搜索限制到特定 OU [和子 OU]

powershell - 如何使用 PowerShell 拆分文本文件?

powershell - 如何确保 IIS 网站在 Powershell 中完全停止?

java - 文件过早结束 - XWPFDocument to PDFConverter

c# - 替换 Word 2003 文档中的 MergeFields 并保持样式