I was wondering if anyone knows what to do. I’m just starting out with Powershell. I have files containing PHP code that is saved in .docx format. I need to edit them in bulk within one folder. This works for me. The problem, however, is that I need it to replace my first level heading:
Introduction
with
Introduction
, then
text
with
text
, then also
text
with
text
and so on up to the tenth level heading, so far I’ve only tried up to 4. However, the problem I’m having is that no matter what I try, only the first heading changes either. Or it changes all of them, but to level 4. My current code changes everything to level 4:
$word = New-Object -ComObject Word.Application
$cesta = "C:\Users\475190\Desktop\Cyber"
if (Test-Path $cesta) {
$subfolders = Get-ChildItem -Path $cesta -Directory
foreach ($subfolder in $subfolders) {
$documents = Get-ChildItem -Path $subfolder.FullName -Filter "*.docx"
foreach ($document in $documents) {
try {
$doc = $word.Documents.Open($document.FullName)
$content = $doc.Content
$content.Text = $content.Text -replace '<h1>(.*?)</h1>', '<h2>$1</h2>' -replace '<h2>(.*?)</h2>', '<h3>$1</h3>' -replace '<h3>(.*?)</h3>', '<h4>$1</h4>'
$doc.Close([ref]$true)
} catch {
Write-Output "Chyba při zpracování souboru '$($document.FullName)': $($_.Exception.Message)"
}
}
}
$word.Quit()
} else {
Write-Host "Vámi zadaná cesta neexistuje, je potřeba správně přepsat umístění složky a poté znovu spustit celý kód"
}
Do you have any tips on what I can do to make it work properly?
I would assume that there is text already in this document, no? If so, could you provide us a quick template of what you’re using? This could help us assist.
Hi, I’m trying to remind myself if anyone has any ideas. And just for clarification - I can’t upload the real text here due to copyright issues. I edit research articles for the journal Cyberpsychology.
You can’t post the text you already posted in image form as actual text? You can’t copy/paste from an image and I for one am not willing to type that out to help you. Please make it easier for us to actually help you.
PHP in a Word document sounds like it’s making the problem more difficult than it needs to be. If you just had the PHP in a text file that would make it easier, I think.
Using the Replace method of the Regex class allows you to use a scriptblock to increment the size by passing in the number it finds. I’ve used non-capturing groups either side of number so only the number gets passed to the scriptblock.
Thank you for the answer. Unfortunately, it converted my php code into the form it would be on the web and was not visible. So I will try what matt-bloomfield advised and possibly try to paste as text.