onefiscus
onefiscus

Reputation: 149

Avoid blank line on Out-File

How can I avoid getting a blank line at the end of an Out-File?

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer)(!(cn=*esx*)) (!(cn=*slng*)) (!(cn=*dcen*)) )'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }`
| Out-File -FilePath C:\Computers.txt

I have tried several options and none of them seem to do anything, they all still have a blank line at the end.

(get-content C:\Computers.txt) | where {$_ -ne ""} | out-file C:\Computers.txt

$file = C:\Computers.txt    
Get-Content $file | where {$_.Length -ne 0} | Out-File "$file`.tmp"
Move-Item "$file`.tmp" $file -Force

Upvotes: 3

Views: 3506

Answers (3)

Akshay
Akshay

Reputation: 11

this the best solution for the avoiding the empty line at the end of txt file using powershell command

Add-Content C:\Users\e5584332\Desktop\CSS.txt "Footer | Processed unique data || $count " -NoNewline

Upvotes: 1

Bacon Bits
Bacon Bits

Reputation: 32145

Often when you're looking to see if strings have no character data, you will want to use String.IsNullOrWhiteSpace():

Get-Content $file | Where-Object { ![String]::IsNullOrWhiteSpace($_) } | Out-File "$file`.tmp"

Upvotes: 0

woxxom
woxxom

Reputation: 73506

Use [IO.File]::WriteAllText:

[IO.File]::WriteAllText("$file`.tmp",
                        ((Get-Content $file) -ne '' -join "`r`n"), 
                        [Text.Encoding]::UTF8)

Upvotes: 3

Related Questions