以前没有这样做过,所以很高兴弄清楚。今天我们俩都要学习!你们非常亲密。只需进行一些调整和一个循环来处理多个文件。我确信会有更有知识的人过来,但这应该会给你带来想要的结果。
$NewDomain1 = "google"
$NewDomain2 = "hij"
$OurDocuments = Get-ChildItem -Path "C:\Apps\testing" -Filter "*.doc*" -Recurse
$Word = New-Object -ComObject word.application
$Word.Visible = $false
$OurDocuments | ForEach-Object {
$Document = $Word.documents.open($_.FullName)
"Processing file: {0}" -f $Document.FullName
$Document.Hyperlinks | ForEach-Object {
if ($_.Address -like "https://www.yahoo.com/*") {
$NewAddress = $_.Address -Replace "yahoo","google"
"Updating {0} to {1}" -f $_.Address,$NewAddress
$_.Address = $_.TextToDisplay = $NewAddress
} elseif ($_.Address -like "http://def.com/*") {
$NewAddress = $_.Address -Replace "def","hij"
"Updating {0} to {1}" -f $_.Address,$NewAddress
$_.Address = $_.TextToDisplay = $NewAddress
}
}
"Saving changes to {0}" -f $Document.Fullname
$Document.Save()
$Pdf = $Document.FullName -replace $_.Extension, '.pdf'
"Saving document {0} as PDF {1}" -f $Document.Fullname,$Pdf
$Document.ExportAsFixedFormat($Pdf,17)
"Completed processing {0} `r`n" -f $Document.Fullname
$Document.Close()
}
$Word.Quit()
让我们来看看它...
我们首先会将您的新地址移至几个变量中,以便将来轻松引用和更改。您还可以在此处添加您要查找的地址,并根据需要替换硬编码字符串。第三行使用过滤器来获取目录中的所有 .DOC 和 .DOCX 文件,我们将使用这些文件进行迭代。就我个人而言,我会小心使用-Recurse
切换,因为您面临着对目录结构中更深层次的文件进行意外更改的风险。
$NewAddress1 = "https://www.google.com/"
$NewAddress2 = "http://hij.com/"
$OurDocuments = Get-ChildItem -Path "C:\Apps\testing" -Filter "*.doc*" -Recurse
实例化我们的 Word Com 对象并将其隐藏在视图中。
$Word = New-Object -ComObject word.application
$Word.Visible = $false
走进我们的ForEach-Object
loop...
对于我们收集的每份文档$OurDocuments
,我们打开它并将所有超链接通过管道传输到另一个ForEach-Object
,我们检查的值Address
财产。如果存在我们想要的匹配项,我们将使用新值更新属性。您会注意到我们也在更新TextToDisplay
财产。这是您在文档中看到的文本,而不是Address
它控制超链接的实际去向。
This... $_.Address = $_.TextToDisplay = $NewAddress1
...是多变量分配的一个例子。自从Address
and TextToDisplay
将被设置为相同的值,我们将同时分配它们。
$Document = $Word.documents.open($_.FullName)
"Processing file: {0}" -f $Document.FullName
$Document.Hyperlinks | ForEach-Object {
if ($_.Address -like "https://www.yahoo.com/*") {
$NewAddress = $_.Address -Replace "yahoo","google"
"Updating {0} to {1}" -f $_.Address,$NewAddress
$_.Address = $_.TextToDisplay = $NewAddress
} elseif ($_.Address -like "http://def.com/*") {
$NewAddress = $_.Address -Replace "def","hij"
"Updating {0} to {1}" -f $_.Address,$NewAddress
$_.Address = $_.TextToDisplay = $NewAddress
}
}
保存所做的任何更改...
"Saving changes to {0}" -f $Document.Fullname
$Document.Save()
在这里,我们为另存为 PDF 时创建新文件名。注意$_.Extension
在我们的第一行。我们切换到使用管道对象来引用文件扩展名,因为当前管道对象仍然是我们的文件信息对象Get-ChildItem
。自从$Document
对象没有扩展属性,您必须对文件名进行一些切片才能获得相同的结果。
$Pdf = $Document.FullName -replace $_.Extension, '.pdf'
"Saving document {0} as PDF {1}" -f $Document.Fullname,$Pdf
$Document.ExportAsFixedFormat($Pdf,17)
关闭文档,循环将移至下一个文件$OurDocuments
.
"Completed processing {0} `r`n" -f $Document.Fullname
$Document.Close()
浏览完所有文档后,我们关闭 Word。
$Word.Quit()
我希望一切都有意义!