Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append results or text to text file by using Powershell

Tags:

powershell

I have a collection of objects with properties: ProductName and PartName. The content of collection is output to a file first:

$colProducts | sort-object ProductName | `
   Select-object ProductName PartName | `
   Format-Table -autosize ProductName, PartName | `
   Out-File myProducts.txt 

So far so good. However, I have trouble to append a text message to the result file like this:

Add-Content myProducts.txt "`nParts in more than one Product`n"

I found that the appended text is not readable at the end. One thing I notice is that the output of the first collection to a file is in Unicode, and the second one code (add-content) is in ASCII if only to a new file.

After this, I would like to continue to add the following information the same result file:

$colProducts | Group-object PartName | sort-object PartName | `
   Where-Object {$_.Count -gt 1 } | `
   Select-object ProductName PartName | `
   Format-Table -autosize ProductName, PartName | `
   Out-File myProducts.txt

The above codes will overwrite to the result file. I need to append to the file. Greatly appreciate help!

Update: It is good to know -Append option. How about Add-Content? It seems adding some unreadable chars to the file after Out-File from collection.

like image 725
Francis Padron Avatar asked Mar 26 '14 20:03

Francis Padron


2 Answers

Try:

$colProducts | Group-object PartName | sort-object PartName | `
   Where-Object {$_.Count -gt 1 } | `
   Select-object ProductName PartName | `
   Format-Table -autosize ProductName, PartName | `
   Out-File -Append myProducts.txt
like image 187
Hunter Eidson Avatar answered Sep 20 '22 15:09

Hunter Eidson


I would first try:

$colProducts | Group-object PartName | sort-object PartName | `
  Where-Object {$_.Count -gt 1 } | `
  Select-object ProductName PartName | `
  Format-Table -autosize ProductName, PartName | `
  Out-File -Append myProducts.txt

And then look at this to get a feel for what you were encountering.

Essentially, Out-File (and Out-File -Append) gives you Unicode by default and Add-Content gives ASCII by default. My advice would be stick to the same command and you shouldn't have a problem.

And, of course, help Out-File -Detailed! Always check out the powershell examples because they help a great deal, not just to figure out their common usage, but to grok them as well.

like image 21
FLGMwt Avatar answered Sep 18 '22 15:09

FLGMwt