Categories

Creating files: 1 *content vs out-file

Ever wondered about the differences between add-content and out-file. They both appear to do the same thing but there is a subtle difference.

Try this

Get-Process | Out-File p1.txt
Get-Process | Add-Content p2.txt
Get-Process | Set-Content p3.txt

If you then do

cat p1.txt

you get

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     64       3      820       2648    33            1768 armsvc
    150       5    15416      14404    50            4708 audiodg
     30       2      492       1936    20            1568 conhost
     56       3     1768       5336    58     0.08   4128 conhost

etc

If you do cat p2.txt or cat p3.txt you will get this

System.Diagnostics.Process (armsvc)
System.Diagnostics.Process (audiodg)
System.Diagnostics.Process (conhost)
System.Diagnostics.Process (conhost)

etc

The Out-File cmdlet sends output to a file. You can use this cmdlet instead of the redirection operator (>) when you need to use its parameters.

The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content. When you pipe an object to Add-Content, the object is converted to a string before it is added to the item. The object type determines the string format, but the format might be different than the default display of the object. This is problem with p2.txt and p3.txt the cmdlet has cast the object to a string not its data.  To control the string format, use the formatting parameters of the sending cmdlet.

Get-Process | out-string | Add-Content p4.txt
cat p4.txt

gives us this

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     64       3      820       2648    33            1768 armsvc
    132       5    15260      14216    49            3436 audiodg
     30       2      492       1936    20            1568 conhost
     56       3     1764       5420    54     2.17   4128 conhost

etc

Leave a Reply