0

I import a CSV file successfully and want to change one value in the PSObject array $ds.

$ds = Import-Csv test.csv -UseCulture
#test.csv content
#A;B
#11;22
#33;44
$ds
$ds.B[1] = 9
$ds

This does not work and nothing else either. This should be very easy I guess. But how?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

2 Answers2

6

You need to access the correct element in the array. The array here is $ds as it contains one object per row. Each row has a B-property that you can read and set. This will work:

#Modify second row's B-value (44) to 9
$ds[1].B = 9

What might confuse you is that $ds.b[1] actually returns 44 while using PowerShell 3.0 or later. This is because of a feature called member enumeration, where $ds.B will return the B-value for every object in the array and then [1] selects the second value which is 44. What's important to know is that member enumeration returns a read-only collection by design, so you can't modify the values that way.

Frode F.
  • 52,376
  • 9
  • 98
  • 114
0

I don't know why that doesn't work.

This does work, however:

$ds = import-csv test.csv -UseCulture
#test.csv content
#A;B
#11;22
#33;44
$ds
$ds[1].B = 9
$ds
Shaneis
  • 1,065
  • 1
  • 11
  • 20
  • You uses different culture settings – mazzy May 18 '18 at 12:03
  • 3
    @mazzy Huh? He's using a different technique to access the value which is why it work.. His culture settings doesn't impact his answer. – Frode F. May 18 '18 at 12:08
  • Should mention that I meant by "I don't know why that doesn't work" I meant I don't know why accessing the row then the value does work but access the column then the value doesn't. @FrodeF. answer fills that in though :) – Shaneis May 18 '18 at 13:01