Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

-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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading