当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] SharePoint Online:如何使用 PowerShell 更新 Word 文档中的链接?

作者:精品下载站 日期:2024-12-14 21:35:32 浏览:13 分类:玩电脑

SharePoint Online:如何使用 PowerShell 更新 Word 文档中的链接?


要求:更新 SharePoint Online 文档库中 Word 文档中的链接。

PowerShell 更新 Microsoft Word 文档中的超链接

在迁移项目中,我们必须替换 SharePoint Online 文档库中存储的 Microsoft Word 文档中嵌入的所有链接。打开每个文档并用新链接更新旧链接会很麻烦。幸运的是,我们可以使用 PowerShell 批量更新 SharePoint Online 文档库中存储的所有 Microsoft Word 文档中的所有超链接(以及链接文本)。


#Variables
$DomainURL = "https://crescent.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com/sites/Funds"
$LibraryName = "Documents"
$OldLink = "National"
$NewLink = "Crescent"

Try
{
    #Connect to SharePoint Online
    Connect-PnPOnline -Url $SiteURL -UseWebLogin
    $Web = Get-PnPWeb

    #Create a new COM object for word
    $Word = New-Object -ComObject Word.Application
    $Word.Visible = $False

    #Get all Word documents from the library
    $Documents = Get-PnPListItem -List $LibraryName -PageSize 500 | Where {$_.FieldValues.FileRef -like "*.doc*"}

    ForEach($Document in $Documents)
    {
        Try
        {
            $DocumentPath = $DomainURL + $Document.FieldValues.FileRef
            Write-host -f Yellow "Processing Document:"$DocumentPath
            #Open the Document
            $WordDocument = $Word.documents.Open($DocumentPath)

            #Get all links from the document
            $Hyperlinks = @($WordDocument.Hyperlinks)

            #Search and Replace Old Links and Text
             $Hyperlinks | ForEach-Object {
                If ($_.Address.ToLower().Contains($OldLink.ToLower()) -or $_.TextToDisplay.ToLower().Contains($OldLink.ToLower()))
                {
                    #Get the current Link and Link Text
                    $CurrentLink = $_.Address
                    $CurrentText = $_.TextToDisplay

                    #Update Link and Description
                    $_.Address =  $_.Address -Replace $OldLink, $NewLink
                    $_.TextToDisplay = $_.TextToDisplay -Replace $OldLink, $NewLink
                    $WordDocument.save()
                    $Document.Update()
                    Write-host -f Green "`tLink '$CurrentText' at '$CurrentLink' has been updated!"
                } 
            }
        }
        Catch {
            write-host -f Red "Document Update Error:" $_.Exception.Message
        }
        Finally {
            $WordDocument.Close()
        }
    }
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}
Finally {
    $Word.quit()
}

该脚本将更改链接文本(描述)以及链接。您可以将其包装在一个函数中以调用多个站点中的所有文档库。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯