Set-Content appends a newline (line break, CRLF) at the end of my file

Viewed 29000

My original config file (web1.config) has no extra line and when viewed in notepad (showing all characters) looks as:

enter image description here

 <?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
  </system.web>
  <appSettings>
    <add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
  </appSettings>
</configuration>

Now, I need to apply the script to change my database name to something else which looks like:

 Move-Item "web1.config" "webtemp.config"
Get-Content "webtemp.config" | ForEach-Object {$_ -replace "database=myDb;", "database=newDb;"} |Set-Content "web1.config" -Force
Remove-Item "webtemp.config"
Write-Output('Settings Changed')

So, the new file (web1.config) generated looks as:

enter image description here

Notice the extra line added at the end of the file (which is completely not needed) I tried all other options such as: - using out-file api - using .net IO method System.IO.StreamWriter - using -nonewline flag (it converts all 10 lines into single line) - using different encoding options - tried replacing \r\n to \r (don't work as again set-content generates the crlf always)

I'm using PowerShell v5.1.

3 Answers

I see that's an xml file. This way doesn't add a newline.

[xml]$xml = get-content web1.config
$xml.configuration.appSettings.add.value = 
  $xml.configuration.appSettings.add.value -replace 'database=myDb;',
  'database=newDb;'
$xml.save("$pwd\web1.config")  # in case of .net weirdness
Related