Format-Table adds a top empty line (row)

I hope you all are doing well!
I am exporting a directory file list to text with the following PS Code:

 Add-Type -AssemblyName System.Windows.Forms
  $saveDialog = New-Object -TypeName System.Windows.Forms.SaveFileDialog
  $PathFiles=(Get-ChildItem c:\temp\Files | Select-Object @{expression={$_.Name};label='Full Name'})
  $RegKeyContent = $PathFiles
  $saveDialog.initialDirectory = [environment]::getfolderpath(“mydocuments”)
  $saveDialog.filter = 'Text file (*.txt)|*.txt|All files (*.*)|*.*';
  $saveDialog.ShowDialog()
  $RegKeyContent | Format-Table * | Out-File $saveDialog.FileName

The code works as should but, when I open the text file there is a empty row on top as shown here:

BlankSpace

I have looked for but I have not been able to find how to remove the top empty line and, make sure the exported text starts on the very top.

Any suggestions is appreciated.
Regards,

Joisrm,
Welcome to the forum. :wave:t4:

Format cmdlets like Format-Table or Format-List and so on are made to be used for formatting console output only and should always be the last cmdlet in a pipeline. If you pipe their output to the next cmdlet it’s in the vast majority of the cases wrong. :wink:

Since you have only one column anyway you could use in this case Out-File directly. If you have a proper table you can use ‘Export-Csv’.
So your last code line could be like this:

 $RegKeyContent | Out-File $saveDialog.FileName

Or like this:

 $RegKeyContent | Export-Csv -Path  $saveDialog.FileName -NoTypeinfromation

In the latter case I’d recommend to cahnge the extension of the file to CSV. :wink:

Hi Olaf,
I am running a PowerShell Runspace within my WinForms C# app. I am providing the user with exporting options such as; Text, HTML and CSV.

I already have all three-export options working. I thought there would be a way to remove the first blank space just to make it look nice.

Thanks.

If you’re using Format-Table to pipe it to the next cmdlet you’re doing it wrong. :point_up_2:t4: Have you tried my suggestion?

The only issue was the empty space on top that I wanted to remove when exporting to text file.

Using your code suggestion gives me the same empty space on top:

$RegKeyContent | Out-File $saveDialog.FileName

Same Top empty space

I already have a code to export to CSV that is working just fine. I do not need another Export-CSV code as you suggested:

 $RegKeyContent | Export-Csv -Path  $saveDialog.FileName -NoTypeinfromation

I have to admit that I did not test my solution. I just assumed that it works. Sorry. :pray:t3:

Try it this way:

($RegKeyContent | Out-String).Trim() | 
    Out-File -FilePath $saveDialog.FileName
($RegKeyContent | Out-String).Trim() | 
    Out-File -FilePath $saveDialog.FileName

Your code worked!

Now Working

Thank you