How can I update a property value at a specific index in a PowerShell CSV array?
Asked by
QuietMaple47
I imported a CSV file with `$data = Import-Csv -Path "path\to\file.csv"` and loop through the resulting collection. I can read individual values with expressions such as `$data.OffLastName[$jj]`, `$data.ReportsToLast[$jj]`, and `$data.ManagerID[$jj]`. However, assigning a new value does not seem to update the original data:
`$Manager = "Manager"`
`$data.ManagerID[$jj] = $Manager`
`$data.ManagerID[$jj]`
The assignment runs without an obvious error, but the final lookup still returns the previous value, such as `$null` or a placeholder string. What is the correct way to modify the `ManagerID` property on the object at index `$jj`?
Answers
The assignment is actually succeeding, but it is being applied to the temporary array created by member-access enumeration. For example:
`$ids = $data.ManagerID`
`$ids[$jj] = $Manager`
`$ids` will show the changed value, while `$data` remains unchanged. To persist the update, modify the object directly with `$data[$jj].ManagerID = $Manager`. This is also safer because the number of values returned through property enumeration is not always guaranteed to match the number of source objects.
Reply to this answer
The capitalization of a property usually is not the problem hereโPowerShell property names are generally case-insensitive. The important distinction is the order of indexing and property access: use `$data[$jj].ManagerID`, not `$data.ManagerID[$jj]`. The first selects one CSV object and changes its property; the second selects an item from an enumerated property-value collection.
Reply to this answer
Index the collection first, then assign the property on that individual object:
`$data[$jj].ManagerID = $Manager`
When you write `$data.ManagerID`, PowerShell uses member-access enumeration to produce a separate list of all the `ManagerID` values. Indexing that list does not directly target the corresponding object inside `$data`, so changing it does not update the imported CSV objects.
Reply to this answer
Add your answer
Answers are reviewed before publication.
QuietMaple47: That worked. I was confusing the list of property values with the original collection. So `$data[$jj].ManagerID` targets the object at that index, while `$data.ManagerID[$jj]` indexes the separately enumerated property values.