question

SuzanaEree-2102 avatar image
0 Votes"
SuzanaEree-2102 asked ·

PowerShell - Select tags between comments

A simple example. I have this lines on 2 different html files, on Folder1 and Folder2. I want to parse (copy) some line from one folder to another, with REGEX, from the tag <tr> to </tr> tag.

The problem is that are a lots of <tr> and <tr> in the file, so I framed between the comments ( <!--START--> and <!--FINNISH--> ) the exact <tr> tags that I want to parse.

 <html>
 <body>
 <table>

 <!--START-->
 <tr>
 new contents
 </tr>
 <!--FINNISH-->

 other lines 

 <tr>
 I love powershell because is hard to understand <tags/>
 </tr>

 other code

 <tr>
 keep stuff including <embedded/> <tags/>
 </tr>

 </table>
 </body>
 </html>

THE PROBLEM: How can I modify this PoweShell Code, as to select (with regex) only those <tr>and </tr> tags that are framed between the comments ( <!--START--> and <!--FINNISH--> )

 $sourceFiles = Get-ChildItem 'c:\Folder1'
 $destinationFolder = 'c:\Folder2'
    
 foreach ($file in $sourceFiles) {
    
 $sourceContent = Get-Content $file.FullName -Raw
 $contentToInsert = [regex]::match($sourceContent,"(?ms)<tr>(.+)</tr>").value
 $destinationContent = Get-Content $destinationFolder\$($file.Name) -Raw
 $destinationContent = $destinationContent -replace '(?ms)<tr>(.+)</tr>)',$contentToInsert
    
 Set-Content -Path $destinationFolder\$($file.Name) -Value $destinationContent -Encoding UTF8
    
 } #end foreach file
windows-server-powershellwindows-server-branch-officewindows-embedded-standard7
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

SuzanaEree-2102 avatar image
0 Votes"
SuzanaEree-2102 answered ·

THE SOLUTION. It was all about a matter of REGEX, I had select all <!--START--> <!--FINNISH--> tags that also contains <tr> </tr> tags, so as to parse only their content


 $sourceFiles = Get-ChildItem 'c:\Folder1'  
 $destinationFolder = 'c:\Folder2'
    
 foreach ($file in $sourceFiles) {
    
 $sourceContent = Get-Content $file.FullName -Raw
 $contentToInsert = [regex]::match($sourceContent,"<!--START-->(\s*)<tr>[\s\S]+</tr>(\s*)<!--FINNISH-->").value
 $destinationContent = Get-Content $destinationFolder\$($file.Name) -Raw
 $destinationContent = $destinationContent -replace '<!--START-->(\s*)<tr>[\s\S]+</tr>(\s*)<!--FINNISH-->',$contentToInsert
    
 Set-Content -Path $destinationFolder\$($file.Name) -Value $destinationContent -Encoding UTF8
    
 } #end foreach file
· 1 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello @SuzanaEree-2102

Thanks for the sharing , kindly mark the answer accepted can help other community members to find useful information.

Have a great day!

Best regards
Karlie

1 Vote 1 ·