Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid blank line on Out-File

Tags:

powershell

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
like image 268
onefiscus Avatar asked Jun 19 '26 14:06

onefiscus


1 Answers

Use [IO.File]::WriteAllText:

[IO.File]::WriteAllText("$file`.tmp",
                        ((Get-Content $file) -ne '' -join "`r`n"), 
                        [Text.Encoding]::UTF8)
like image 95
wOxxOm Avatar answered Jun 22 '26 03:06

wOxxOm