'Powershell - Set-Content adding characters to line instead of overriding

I am trying to override my contents within a json file but the contents keep adding to the line and not overriding. What did I do incorrectly?

$ActualContent = '"line1": "0 21 * * *'
$ContentToReplace = '"line1": "0 23 * * *'


Content = Get-Content $BaseFolder\$FileName -Raw 

# Change Content
$Content -replace $ActualContent,$ContentToReplace | Set-Content $BaseFolder\$FileName

Write-Host " The content $ActualContent has been replaced with $ContentToReplace" -ForegroundColor Green

Before code : "line1": "0 21 * * *" After code : line1": "0 23 * * ** * *"

I did notice that if I add the " to the end then the script doesnt work.



Solution 1:[1]

What you're experiencing is easy to reproduce:

$content = '"line1": "0 21 * * *"'
$ActualContent = '"line1": "0 21 * * *'
$ContentToReplace = '"line1": "0 23 * * *'
$content -replace $ActualContent, $ContentToReplace # => "line1": "0 23 * * ** * *"

This is because the replacement operator -replace uses regex to find patterns and replace them. * is a special character, if you were looking to match a literal * you would need to escape it using \.

  • $contentToReplace would become:
$ContentToReplace = '"line1": "0 23 \* \* \*'

Use https://regex101.com/r/hJZeos/1 to understand better what's going on.

Your issue should be easily fixed using the .Replace(...) string method which will match strings literally:

$content = '"line1": "0 21 * * *"'
$ActualContent = '"line1": "0 21 * * *'
$ContentToReplace = '"line1": "0 23 * * *'
$content.Replace($ActualContent, $ContentToReplace) # => "line1": "0 23 * * *"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1