powershell - PowerShell 不会遍历文档
问题描述
PowerShell 脚本不会遍历文档来更改文档中的每个超链接。
该脚本通过 SharePoint Online 上的文档库运行,并且可以打开库中的每个文档。然后它应该遍历每个文档并提取它找到的任何超链接,然后将超链接分成两部分。然后,该脚本应将后半部分添加到新 URL 中,并将地址更新为新的更新 URL。
add-type -AssemblyName "Microsoft.Office.Interop.Word"
$wdunits = “Microsoft.Office.Interop.Word.wdunits” -as [type]
$donotsave = “Microsoft.Office.Interop.Word.wdDoNotSaveChanges” -as [type]
$save = “Microsoft.Office.Interop.Word.wdSaveChanges” -as [type]
$application = New-Object -ComObject Word.Application
$application.Visible = $false
$tenancy = "https://tenancy.sharepoint.com"
$url = "https://tenancy.sharepoint.com/sites/siteName/"
Connect-PnPOnline -Url $url -UseWebLogin
$library = Get-PnPList | Where-Object {$_.Title -eq "libraryName"}
$items = Get-PnPListItem -List $library
foreach ($item in $items) {
if ($item["FileLeafRef"] -match ".doc*") {
Write-Host "File Name: "$item["FileLeafRef"]
$item["FileLeafRef"]
$item["FileRef"]
Write-Host `
$documentLocation = "https://tenancy.sharepoint.com"+$item["FileRef"]
$documentLocation
$document = $application.Documents.Open($documentLocation)
$docURLS = @($document.Hyperlinks)
$docURLS | foreach{
Start-Sleep -Seconds 7
$newURI = ([uri]$_.address).AbsoluteUri
$result = $newURI.Split("=") | Select-Object -Skip 1 -First 1
$result
$newUrl = "https://tenancy.sharepoint.com/sites/siteName/_layouts/DocIdRedir.aspx?ID="+$result
$_.address = $newUrl
Write-Verbose ("Updating {0} to {1}" -f $_.Address,$newUrl) -Verbose
}
$document.save()
$document.close([Ref]$save)
$item.File.Update()
}
}
$application.quit()
Disconnect-PnPOnline
该脚本当前可以遍历库并打开每个文档,当文档中有多个超链接时会出现问题。它正确更改了第一个 URL,但之后的所有其他链接都会收到以下错误:
对象已被删除。在 C:\filepath.ps1 :36 char:5 + $_.address = $newUrl
调用的对象已与其客户端断开连接。(来自 HRESULT 的异常:0x80010108 (RPC_E_DISCONNECTED))在 C:\filepath.ps1:39 char:9 + $document.save()
调用的对象已与其客户端断开连接。(来自 HRESULT 的异常:0x80010108 (RPC_E_DISCONNECTED))在 C:\filepath.ps1:40 char:9 + $document.close([Ref]$save)
您不能在空值表达式上调用方法。在 C:\filepath.ps1:33 char:5 + $result = $newURI.Split("=") | 选择对象 - 跳过 1 - 第一个 1
解决方案
如果 $_.address 值像“/sites/team?ID=1”,则 $newURI 将为空,然后运行 $newURI.Split("=") | Select-Object -Skip 1 -First 1 将得到“您不能在空值表达式上调用方法”。
您可以在使用 $newURI.Split 方法之前检查 $newURI 是否为空。
或者我们可以替换下面的代码。
$newURI = ([uri]$_.address).AbsoluteUri
$result = $newURI.Split("=") | Select-Object -Skip 1 -First 1
和
if($_.Address)
{
$result = $_.Address.Split("=") | Select-Object -Skip 1 -First 1
}
else
{
$_
}
推荐阅读
- perl - 用于 grep 的 Perl 脚本始终阻止并打印指定的行
- go - go中如何使用通道?
- angular - '[value]' 没有以反应形式 Angular 设置控制值
- reactjs - 无法在 react-native 中创建 ref
- netlogo - 如果它在netlogo的某个半径内,如何阻止海龟一段时间并杀死两只海龟
- laravel - 如何在 Laravel 登录中阻止 GET 方法?
- c# - 为什么不 AsyncUnaryCall
和其他人扩展任务 ? - c# - 使用 Continuation 链接任务的正确方法
- git - 如何列出存储库中的所有提交及其父信息以及使用命令行或 JGit 添加和删除的行?
- json - 无法检索参数输出的值