Joisrm
October 25, 2022, 4:29pm
1
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:
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,
Olaf
October 25, 2022, 6:50pm
2
Joisrm,
Welcome to the forum.
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.
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
.
Joisrm
October 25, 2022, 9:34pm
3
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.
Olaf
October 25, 2022, 11:45pm
4
If you’re using Format-Table
to pipe it to the next cmdlet you’re doing it wrong. Have you tried my suggestion?
Joisrm
October 26, 2022, 1:44am
5
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
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
Olaf
October 26, 2022, 6:58am
6
I have to admit that I did not test my solution. I just assumed that it works. Sorry.
Try it this way:
($RegKeyContent | Out-String).Trim() |
Out-File -FilePath $saveDialog.FileName
Joisrm
October 26, 2022, 11:55am
7
($RegKeyContent | Out-String).Trim() |
Out-File -FilePath $saveDialog.FileName
Your code worked!
Thank you