powershellsitecoresitecore-rocks

Powershell Replace Variable in String


I have a string in a config file that contains a $ character.
I want to replace this line but powershell recognize this as a variable.
I have done some research and found that "" = variable and ''=regex.
And using backtick ` should work but I can't get it to work.

Line to replace :

<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />

Replace with this :

<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>\n          <remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />

What I currently have :

$replace = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>';
$with = ('<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20"    minAge="7.00:00:00"/>\n          <remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />');
(Get-Content $webConfigFileName) -replace $replace,$with | Set-Content $webConfigFileName;
Write-Output "Replaced '$replace' with '$with' in $webConfigFileName";

Can someone help me with a solution for this?


Solution

  • In most cases you can use single quotes which will treat everything inside them as literal rather than interpreting things such as variables. In some cases this can be problematic with multiple nested quotes in which case you need to start escaping or use a here string, however in this situation it is not required.

    You actually need to use regex escapes in your matching statement for a few different areas to get this to work and then wrap everything in single quotes to make it function.

    $1 = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00" />'
    $REGEX = '<remove folder="\$\(dataFolder\)\/logs" pattern="log\.\*\.txt" maxCount="20" minAge="7\.00:00:00" \/>'
    $1 -replace $regex,'test'
    

    Edit: the txt you want to replace with can also be enclosed in single quotes and it will work, like this:

    $1=gc C:\test.txt
    $REGEX = '<remove folder="\$\(dataFolder\)\/logs" pattern="log\.\*\.txt" maxCount="20" minAge="7\.00:00:00" \/>'
    $replace = '<remove folder="$(dataFolder)/logs" pattern="log.*.txt" maxCount="20" minAge="7.00:00:00"/>          
    <remove folder="$(dataFolder)/logs" pattern="WebDAV.log.*.txt" maxCount="20" minAge="7.00:00:00" />'
    $1 -replace $regex,$replace | set-content c:\test.txt