Share via


Powershell - Replacing text and inserting a new line in a file with "\ character

Question

Friday, April 26, 2013 6:02 PM

Greetings all,

I'm trying to automate updating a configuration file at remote sites.  I need to replace a string in a line, then insert a new line below it with another string.

So from this:

*     Sometext*

     SessionConfig=All \

*     Sometext*

To this:

*     Sometext*

*     SessionConfig=ICA \*

*     Sessionreliability=YES \*

*     Sometext*

I've gone at this many different ways, each one failing.  depending on the script I get something like this:

*     SessionConfig=All SessonConfig=YES \*

Or some other bad variation.  Below is one attempt:

*$replacement="SessionConfig=ICA \ `nSessionReliability=YES \*

(get-content wnos.ini) | foreach-object {$_ -replace "SessionConfig=All \,$replacement}|set-content wnos.ini

And another that just tries to add the new line:

*(get-content $filename) |*

foreach-object

{

$_

if ($_ -match "SessionConfig=ICA \)

*     {*

*     "SessionReliability=YES \*

*     }*

} |set-content $file

Any help would be appreciated, thanks.



All replies (5)

Friday, April 26, 2013 7:26 PM ✅Answered | 1 vote

Hi,

try this.

Best regards
brima

$Text = get-content text.txt
$NewText = @()
foreach ($Line in $Text) {
    if ($Line -eq "SessionConfig=All \") {
        $Line = $Line.Replace("All \", "ICA \")
        $NewText += $Line
        $NewText += "Sessionreliability=YES \"
    }
    else {
        $NewText += $Line
    }
}
$NewText | Set-Content newtext.txt

PS E:\temp\Source> $text
Sometext
SessionConfig=All \
Sometext

PS E:\temp\Source> $NewText
Sometext
SessionConfig=ICA \
Sessionreliability=YES \
Sometext


Friday, April 26, 2013 6:47 PM

i did something like this

$replacement="SessionConfig=ICA \ `nSessionReliability=YES \"
(get-content wnos.ini) -replace "\W(.+?All \\)\W",$replacement

you could of done

-replace "sessionconfig=all [\",$replacement](file://\)


Friday, April 26, 2013 7:29 PM

Here comes just another proposal:

$str1 =@'
Sometext
SessionConfig=All \
Sometext
'@
$str1 -replace "All \\\r", "ICA \`r`nSessionreliability=YES \"

Kind regards,

wizend


Friday, April 26, 2013 7:48 PM

Hi Wizend,

i try your proposal this work here not.
i Change the regex, now it works.

$str1 -replace "All \\B", "ICA \nSessionreliability=YES \

Best regards
brima

$text = Get-Content text.txt
$NewText = $Text -replace "All \\\B", "ICA \`nSessionreliability=YES \"
$NewText | Set-Content newtext.txt

Friday, April 26, 2013 10:29 PM

Thanks brima, that did it for me.  For some reason the other scripts kept putting the strings on the same line like this:

Sessionconfig=ICA \ Sessionreliability=YES \

Thanks to all for your contributions.