PowerShell: Appending CSV Data

To append a CSV file with new data, first of all make sure the type of data you append is the same type of data already in a file (or else column names will not match).

This creates a list of unique running processes (so it will not list duplicate process names):

$filepath = "$env:temp\processes.csv"

Get-Process | Select-Object Name, Company, Description -Unique |
Export-Csv $filepath -UseCulture -NoTypeInformation -Encoding UTF8

Let’s assume you’d like to append new processes to that list, so whenever you run the following code, you want it to check whether there are new processes, and if so, add them to the CSVfile:

$filepath = "$env:temp\processes.csv"
# get names of old processes:
$oldproc = Import-CSV $filepath -UseCulture | 
  Select-Object -expand Name
# get new processes that are not in that list already:
$newproc = Get-Process | Where-Object { $oldproc -notcontains $_.Name } |
  # make sure you select the same information as present in the original CSV file:
  Select-Object Name, Company, Description |
  # output progress:
  ForEach-Object {
    Write-Warning "Found new process: $($_.Name)"
  } |
  # save new processes as CSV. Make sure to use the same delimiter:
  ConvertTo-CSV -UseCulture
# add new CSV to the old file. Make sure to use same encoding:
$newproc[2..$($newproc.Count-1)] | Out-File -Append $filepath -Encoding UTF8
# open new file:
notepad $filepath

One Response to “PowerShell: Appending CSV Data”

  1. Chris Jorgensen October 22, 2013 at 8:57 pm #

    Great info, Adapted this to Get-ADUser for a number of OU’s and one excel file.

Leave a Reply

revia in alcoholism