powershellmember-enumerationmember-access-enumeration

How do I edit the values of imported CSV variable with PowerShell


The below script is an example of me importing a CSV file, trying to edit one of the values, then checking the value.

$Animal_Farm = Import-CSV "Test.csv"

Echo "The Data"
$Animal_Farm

Echo "`n`n`n"

Echo "Dog's Status"
$Animal_Farm.Status[1]
Echo "`n`n`n"

Echo "Updating Dog's Status to Employed"
$Animal_Farm.Status[1] = "Employed"
Echo "`n`n`n"

Echo "Dog's Status"
$Animal_Farm.Status[1]

This is the output, the data is unchanged and Dog's status is still Redundant.

The Data

Animal Ocupation    Status   
------ ---------    ------   
Cat    Construction Employed 
Dog    Professional Redundant
Rat    GP           Employed 




Dog's Status
Redundant




Updating Dog's Status to Employed




Dog's Status
Redundant

How do I edit the data imported? My plan is to feed the modified data into a JSON file.

This is the CSV file contents

Animal,Ocupation,Status
Cat,Construction,Employed
Dog,Professional,Redundant
Rat,GP,Employed

Solution

  • $Animal_Farm holds an array of objects, each of which have a Status property.

    When you ask PowerShell to resolve $Animal_Farm.Status, PowerShell goes "huh, the $Animal_Farm array doesn't have a Status property, let me create a new array from the Status property values of each item in the array", which is what you eventually index into with $Animal_Farm.Status[1].

    To address the properties of one of the underlying items in the original array, use the index operator directly on $Animal_Farm instead:

    $Animal_Farm[1].Status