1

I'm writing a PowerShell script to update a Word document's content in the SharePoint Online Document Library.

Below is the script so far. The issue is the $document variable value is null when trying to get the file from SharePoint.

I've debugged the $documentLocation. The value is valid and the correct location of the file. Also, I've tried to change the $documentLocation with a file located in a public site (not SharePoint). The result is $document value is not null.

Are there any missing steps in my script below?

add-type -AssemblyName "Microsoft.Office.Interop.Word"
$save = "Microsoft.Office.Interop.Word.wdSaveChanges" -as [type]
$application = New-Object -ComObject Word.Application
$application.Visible = $false

$url = "https://{tenant}.sharepoint.com"

Connect-PnPOnline -Url $url -Credentials (Get-Credential)

$library = Get-PnPList | Where-Object {$_.Title -eq "Documents"}
$items = Get-PnPListItem -List $library
foreach ($item in $items) {
  if ($item["FileLeafRef"] -match ".doc*") {
    Write-Host "File Name: "$item["FileLeafRef"]  
    $documentLocation = -join ($url, $item["FileRef"])
    $document = $application.Documents.Open($documentLocation)

    # TODO: Update content

    $document.save()
    $document.close([Ref]$save)
    $item.File.Update()
  }
}

$application.quit()
Disconnect-PnPOnline
0

Why edit the content? Just replace whole document every metadata will remain and no new version will be created. But here is -Stream so you can try update with this cmd not just replacing.

Microsoft Documentation

Great Example

  • Because I need to replace some particular words from the content. Is it possible to do that with Add-PnPFile? – Ari Gunawan Jan 31 at 15:40
  • Yes it should be possible, but I havent time to test it, so you can try it – Zdeněk Vinduška Jan 31 at 16:01
  • How can I get the content to be upload? Should I download the file > open the file in local > update the file > upload the file to SharePoint? I want to replace some words only from the footer of Word document. – Ari Gunawan Feb 1 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.