Home > Software engineering >  powershell convert a list of csv values (PSCustomObject) to integer
powershell convert a list of csv values (PSCustomObject) to integer

Time:06-10

i read a csv file into a variable using Import-CSV. Now when I try to print a list of all values of a certain property, I can see through GetType() that these are not Integer values but rather "PSCustomObjects". How can i convert all of these values into integer? I need to do manipulations like Sort-Object etc.

I tried doing some typecasts i found in other threads like so:

[int]($MyArray | select -ExpandProperty Level)

but they arent working because I get an error that its not possible to convert from pscustomobject to int or whatever. I don't even know what this object is supposed to be, I mean i can see the list contains numbers, so why arent they either string or integer...Sometimes powershell is driving me crazy.

Thanks for the help

CodePudding user response:

The correct cast to an array of int is:

[int[]]($MyArray | select -ExpandProperty Level)

You can make this shorter by using member access enumeration:

[int[]] $MyArray.Level

Another way is to use the intrinsic ForEach method, which has an overload for type casting:

$MyArray.Level.ForEach([int])

In this case we don't specify an array type, because ForEach applies the type cast to each element individually. This might be handy if you want to chain more methods like this:

$MyArray.Level.ForEach([int]).Where{ $_ -gt 2 }

To follow the execution order of the statement we can linearly read it from left to right. Compare with an array cast, which is more difficult to follow because of the parentheses:

([int[]] $MyArray.Level).Where{ $_ -gt 2 }
  • Related