Replace First Occurrence of a String in a Multi-line String with PowerShell


Again a very simple post about a simple thing which I cannot find a satisfactory answer for on the Internet.
How do you replace the first instance of a string in a multiline string in PowerShell?
You have the following and you want to replace the first “<tr>”.

<table>
    <tbody>
        <tr>
               <td>2017-12-12 01:39:40</td>
               <td>User Provisioning Completed</td>
        </tr>
    </tbody>
</table>

Latest versions of PowerShell have 3 arguments for the "replace" method with the last one being exactly that – the number of occurrences from the beginning that will be replaced. But I write scripts that have to run in numerous environments and adding PowerShell update prerequisite just for that seems like overkill.
My exact scenario is that I want to add a value in the top of a table, so I’m replacing the first “<tr>” with the new value and keeping this existing “<tr>”.
Here is my solution:

####This is the string that we will replace in
$initialString = @"
<table>
    <tbody>
        <tr>
               <td>2017-12-12 01:39:40</td>
               <td>User Mail Created</td>
        </tr>
    </tbody>
</table>
"@

####This is the string that will be the replacement.
$ireplacementString = @"
<tr>
               <td>2017-12-12 01:50:17</td>
               <td>User Provisioning Completed</td>
        </tr>
        <tr>
"@


####Add Regex to Replacement String
$replacementConstruct=@'
$1{0}
'@ -f $ireplacementString

####Replace the first occurance of "<tr>" with the content of Replacement String.
$finalResult = $initialString -replace '^((?s).*?)<tr>', $replacementConstruct 

Comments