Reading & Writing CSV files RRS feed

  • Question

  • I am trying to read a CSV file and update one field (from user input) and write back to the same record in the CSV.  I am finding a lot of examples out there but none that talk about updating that record I read in and modified.  I am new to PS so still learning but would like some help.

    CSV file format:



    zone1, server1,,ADD,A,,Windows,Fred, 3/3/2018 2:15pm

    Tuesday, April 10, 2018 7:39 PM

All replies

  • You cannot output to the same file you are reading. 

    Import-Csv file1.csv |
               # update records
          } |
          Export-Csv file2.Csv

    I highly recommend doing the following tutorial before you attempt to use PwoerShell.

    Learn PowerShell  
    PowerShell Documentation
    PowerShell Style Guidelines


    Tuesday, April 10, 2018 7:54 PM
  • Well, I did a little reading and you can output to the same file, using the get-content and then set-content cmdlets it seems.   Now sure how I can use this code though for what I am doing.

    (Get-Content"c:\temp\Notice.txt"|ForEach-Object{$_-replace"Warning","Caution"}) |Set-Content"C:\temp\Notice.txt"

    Tuesday, April 10, 2018 8:40 PM
  • You can but it is dangerous because you can lose the file if there is an error.

    The correct code is this.

    (Import-Csv file.csv) | ForEach{ $_.column = $_.Column -replace 'xxx','yyy'}|Export-Csv file.csv

    I do not recommend it as it serves no real purpose and using a separate file guarantees that you won't corrupt or lose the original.

    Parens around an operation cause the operation to complete before sending into the pipeline.


    Tuesday, April 10, 2018 9:09 PM
  • Ok, I can understand that.  What I am trying to do is maintain information in a CSV file and allow the user to update the same file. It would read in the record and display it for them and allow them to update a single field and then write back update field back to the same file.  Don't need multiple output files, need this to be done in a single file.  I am using Powershell Suite application with a GUI frontend to this file.
    Tuesday, April 10, 2018 9:20 PM
  • You can easily load a csv into a DataGridView, edit it and save it back to the same file.  Of course your original question was only about using simple PS.  The GUI method requires good PowerShell skills as well as good skills with Windows Forms.

    Here is an example of editing a CSV with a form.!AjiiPtIUqzK_hdth4coCPZMopbhlZQ


    Tuesday, April 10, 2018 9:27 PM
  • This is all of the code required to edit a CSV (minus form display code).

    	$csv = Import-Csv myfile.csv
        $datagridview1.DataSource = ConvertTo-DataTable $files
    $buttonExportCsv_Click = {
    	$datagridview1.SelectedRows | 
    		Select-Object -expand DataBoundItem |
    		Export-csv myfile.csv -notype


    Tuesday, April 10, 2018 9:28 PM