Miha Žitko
Miha Žitko

Reputation: 83

Replacing text in one property of an array

I have a large array with data with many properties. One of those properties is Value, but is formatted as NoteProperty, probably since the containing numbers use a comma instead of a dot for decimal separation.

I want to sum the Value from each line of array depending on other properties in the array but can't since the Value property is not an integer.

Is there a way to replace comma to dot only in one Property not all Properties in the array since I want to keep other properties intact?

Example:

$data1 = @(
[pscustomobject]@{No='1';Name='Joe';Service='Subscription,1';Price='5'}
[pscustomobject]@{No='2';Name='Sue';Service='Subscription,2';Price='4'}
[pscustomobject]@{No='3';Name='Joe';Service='Call Price,1';Price='0,1'}
[pscustomobject]@{No='4';Name='Sue';Service='Call Price,2';Price='0,2'}
[pscustomobject]@{No='5';Name='Sue';Service='Call Price,1';Price='0,1'}
[pscustomobject]@{No='6';Name='Joe';Service='Call Price,2';Price='0,2'})

$data | get-member

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
Name        NoteProperty string Name=Joe               
No          NoteProperty string No=1                   
Price       NoteProperty string Price=5                
Service     NoteProperty string Service=Subscription,1

Upvotes: 0

Views: 470

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Use Select-Object to create new objects where the Price property has had its value replaced:

$data1 = $data1 |Select Name,No,@{Name='Price';Expression={($_.Prices -replace ',','.') -as [double]}},Service

Now you can sort the objects by the numerical value of Price:

PS ~> $data1 |Sort-Object Price

Name No Price Service
---- -- ----- -------
Sue  5    0.1 Call Price,1
Joe  3    0.1 Call Price,1
Sue  4    0.2 Call Price,2
Joe  6    0.2 Call Price,2
Sue  2      4 Subscription,2
Joe  1      5 Subscription,1

Upvotes: 1

Related Questions