Elvar
Elvar

Reputation: 454

Parse an object and add a member property to each member

I have an object which looks for example like this

Name      Number
----      ------
John      one
Major     two
Mars      one

I want to go through each member and check on Number and add a property that in the end it looks like this.

Name      Number     IsItOne
----      ------     -------
John      one        True
Major     two        False
Mars      one        True

What I got so far is do a foreach loop through the object but then I have two objects and have no chance as far as I know to change the original object.

Upvotes: 2

Views: 441

Answers (3)

Doug Finke
Doug Finke

Reputation: 6823

Here is a possible alternative.

function new-stuff ($name, $number) {
    New-Object PSObject -Property @{name=$name; number=$number}
}

$(
    new-stuff John  one
    new-stuff Major two
    new-stuff Mars  one
) | ForEach { $_ | Add-Member -PassThru ScriptProperty IsItOne {$this.Number-eq"one"} }

Upvotes: 2

Shay Levy
Shay Levy

Reputation: 126752

Just another (shorter) version:

$obj | add-member -type scriptproperty -name IsItOne -value {$this.Number -eq 'one'} -passthru

Upvotes: 4

manojlds
manojlds

Reputation: 301157

It seems to be like you are talking about a set of objects with properties Name and Number.

If so, you can do like this:

$a | %{  $isitone = $false; if($_.Number -eq "one") {$isitone=$true} $_ | 
         add-member -Type noteproperty -name IsItOne -value $isitone  }

Upvotes: 3

Related Questions