Search code examples
windowspowershellcsvexport-to-csv

PowerShell: Difference between (ConvertTo-* | Set-Content) and (Export-*)?


I'm new to PowerShell, and trying to learn things the write way, I noticed in this case that I can export data in many different manners, what I want to ask about is this case,

Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt

and :

 Get-Process | Export-Csv -Path .\Process.txt

Both exports the list of the processes into a CSV file on my desktop, and give the same result.

The first one :

Converts the processes to CSV first then it writes it onto the file.

The second one :

Exports the Processes directly to the file.

What's really the difference between the two cases, is there performance difference, time execution difference, or anything else I'm not aware of ?


Solution

  • They are pretty much the same. There shouldn't be any big difference when it comes to performance and time:

    Measure-Command { Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt }  
    
    Days              : 0
    Hours             : 0
    Minutes           : 0
    Seconds           : 2
    Milliseconds      : 880
    Ticks             : 28801761
    TotalDays         : 3,33353715277778E-05
    TotalHours        : 0,000800048916666667
    TotalMinutes      : 0,048002935
    TotalSeconds      : 2,8801761
    TotalMilliseconds : 2880,1761 
    
    Measure-Command { Get-Process | Export-Csv -Path .\Process2.txt }
    
    Days              : 0
    Hours             : 0
    Minutes           : 0
    Seconds           : 2
    Milliseconds      : 772
    Ticks             : 27724661
    TotalDays         : 3,20887280092593E-05
    TotalHours        : 0,000770129472222222
    TotalMinutes      : 0,0462077683333333
    TotalSeconds      : 2,7724661
    TotalMilliseconds : 2772,4661
    

    This is because Export-CSV and ConvertTo-CSV run 90% of the same code. They share the same helper-class Microsoft.PowerShell.Commands.ExportCsvHelper to create the header and convert objects to csv. The only difference is that ConvertTo-CSV writes the CSV-object(string) to the pipeline using WriteObject(), while Export-CSV directly writes it to a file using a StreamWriter.

    To find this yourself, you could look inside Microsoft.PowerShell.Commands.Utility.dll. I won't be posting the code directly because I'm not sure if it's legal or not. :-)

    If you need the CSV-output to be displayed or sent through a third-party API etc., then use ConvertTo-CSV. If you need the data stored in a CSV-file, then you should use Export-CSV.