Search code examples
powershellpowershell-5.0

PowerShell not removing new line characters


Environment: Windows 10 pro 20H2, PowerShell 5.1.19041.1237

In a .txt file, my following PowerShell code is not replacing the newline character(s) with " ". Question: What I may be missing here, and how can we make it work?

C:\MyFolder\Test.txt File:

This is first line.
This is second line.
This is third line.
This is fourth line.

Desired output [after replacing the newline characters with " " character]:

This is first line. This is second line. This is third line. This is fourth line.

PowerShell code:

PS C:\MyFolder\test.txt> $content = get-content "Test.txt"
PS C:\MyFolder\test.txt> $content = $content.replace("`r`n", " ")
PS C:\MyFolder\test.txt> $content | out-file "Test.txt"

Remarks

The above code works fine if I replace some other character(s) in file. For example, if I change the second line of the above code with $content = $content.replace("third", "3rd"), the code successfully replaces third with 3rd in the above file.


Solution

  • You need to pass -Raw parameter to Get-Content. By default, without the Raw parameter, content is returned as an array of newline-delimited strings.

    Get-Content "Test.txt" -Raw
    

    Quoting from the documentation,

    -Raw

    Ignores newline characters and returns the entire contents of a file in one string with the newlines preserved. By default, newline characters in a file are used as delimiters to separate the input into an array of strings. This parameter was introduced in PowerShell 3.0.