0

I have a need to update the DOCX file content using SharePoint 2013 PowerShell. I am using below code to do the same, but once file gets updated and checked in by the code, the files getting corrupted and don't open in word application. So, please let me know if anyone have done such requirement.

foreach ($file in $folder.Files){ Write-Host $file.Name Write-Host $file.CheckOutType $file.CheckOut() $BinaryContent= $file.OpenBinary() $encode = New-Object System.Text.ASCIIEncoding $ContentString = $encode.GetString($BinaryContent) Write-Host -BackgroundColor Cyan $ContentString $ContentString = $ContentString -replace "kailash","KCS" $file.SaveBinary($encode.GetBytes($ContentString)) $file.CheckIn("modified by code") }

Any help is appreciated.Thanks in advance!

0

You need to use Open XML SDK to achieve the requirement. My suggestion is to use SharePoint .NET Client Object Model using C# and convert you PowerShell script to perform similar action, i.e.

  • Loop through all files under a SharePoint document library,
  • Check out the file
  • Download the file to local
  • Use open XML SDK WordprocessingDocument class to load the DOCX file and add/ replace text.
  • Upload the file to same document library with same name, which should add it as a new version to the existing file.
  • Check in the file.

Here is the link to Open XML SDK tutorial to replace text in a word (DOCX) document.

Option: If you want to keep your PowerShell code, then you can look at calling C# code from PowerShell using reflection. So, you can keep your PowerShell code to check in the file then pass the file url to your C# code method, which would download that file and perform remaining action till checking it in. At this point the control would be transferred to your PowerShell code, indicating a successful operation and it would just check the file in to complete the operation.

Hope this helps you.

  • Hi, Thanks for the reply.I am now able to update the new link, but unable to update the hyperlink text or anchor text..Can you help me on this please? – Kailash Sahoo Jun 16 at 13:48
0

This may not be the answer you are looking for, but I wanted to share what I have. I have been able to update contents of docx file using VB script and it was pretty simple. Here is a little sample. I hope it helps

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(strDocFilename)

With objDoc.PageSetup
    .Orientation = wdOrientLandscape
    .TopMargin = objWord.InchesToPoints(0.25)
    .BottomMargin = objWord.InchesToPoints(0.25)
    .LeftMargin = objWord.InchesToPoints(0.25)
    .RightMargin = objWord.InchesToPoints(0.25)
End With
objDoc.Save

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.