Check if there is a new line in a text file

Hi,

I am using add-content to add a new line of text to an existing text file. for example:

add-content -Path .\test.txt -Value "line2"

The problem is that sometimes this text file might be edited manually, and someone forgets to press enter to take the cursor to the next line. Then the above command would add “line2” to the end of the existing text.

text file:

line1line2

If I try to use the following:

add-content -Path .\test.txt -Value "`nline3"

text file:

line1line2
line3

it works if the above scenario occurs, but after that I get a blank line:

add-content -Path .\test.txt -Value "`nline4"

text file:

line1line2
line3

line4

Is there a way to check if there is a new line at the end of the text file or if the end of the text file ends on a line with some text?

Depending on the actual task you could read the whole file with Get-Content, add the new content and write the file back completely. In this case it does not matter if there is an empty line at the end or not.

$Content = Get-Content -Path '.\test.txt'
$NewContent = $Content + 'line2'

$NewContent | 
    Set-Content -Path '.\test.txt' -Force
2 Likes

Thanks seems simple and does the job