PowerShell replace text between two strings with date and time

Viewed 113

I been trying to figure out how to do the following in PowerShell but without much luck.

I want to replace everything between messageid> AND </messageid with the current date and time.

I have started writing some code as pasted below, can someone direct me in the right path - much appreciate it.

Get-Content -path C:\test.txt -raw -replace pattern = "(?s)messageid>(.*?)</messageid"'<message>*</messageid>' (Get-Date).ToString('dddd dd-MM-yyyy HH:mm:ss') | Set-Content -path c:\test.txt
1 Answers

This example should help you achieve your desired result.

$text = @'
Some line of text
random text <messageid> who knows </messageid> some other text
another line
'@

$text -replace '(?s)(?<=messageid>).+?(?=</messageid)',(Get-Date).ToString('dddd dd-MM-yyyy HH:mm:ss')

Some line of text
random text <messageid>Monday 12-10-2020 21:54:04</messageid> some other text
another line

Edit

And applied to the example from your comment

'<MessageID>9348399343-38493-Det-100</MessageID>' -replace '(?s)(?<=messageid>).+?(?=</messageid)',(Get-Date).ToString('dddd dd-MM-yyyy HH:mm:ss')

<MessageID>Monday 12-10-2020 21:58:56</MessageID>
Related