'Powershell Set-Content fails for one file and succeeds for another?

Trying to modify to different files and getting two different outcomes. The successful file "autoexec.cfg works fine. Here is the file contents and powershell code. c:\temp\autoexec.cfg contains:

disable_write_track = true
webgui_port = 8470

powershell code to modify file:

$WGP = get-random -minimum 8000 -maximum 8999
$line = Get-Content "C:\temp\autoexec.cfg" | Select-String webgui_port | Select-Object -ExpandProperty Line
$content = Get-Content "C:\temp\autoexec.cfg"
$content | ForEach-Object {$_ -replace $line,"webgui_port = $WGP"} | Set-Content "C:\temp\autoexec.cfg"

The file that fails sets up like this. c:\temp\serverSettings.lua contains:

cfg = 
{
    ["port"] = 10302,
} -- end of cfg

powershell code to modify file

$DCSP = get-random -minimum 10000 -maximum 19999
$line = Get-Content "C:\temp\serverSettings.lua" | Select-String port | Select-Object -ExpandProperty Line
$content = Get-Content "C:\temp\serverSettings.lua"
$content | ForEach-Object {$_ -replace $line,"    [\`"port\`"] = $DCSP,"} | Set-Content "C:\temp\serverSettings.lua"

The file does not change except it does. I have the file open in Notepadd++ and after running the code Notepad++ sees the file has been changed and wants to reload but there are no changes.



Solution 1:[1]

-replace is a regex operator, and [] is a special construct in a regular expression and needs to be escaped properly.

The easiest way to do that is with [regex]::Escape():

$content | ForEach-Object {$_ -replace [regex]::Escape($line),"    [\`"port\`"] = $DCSP,"} | Set-Content "C:\temp\serverSettings.lua"

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 Mathias R. Jessen