AdilZ
AdilZ

Reputation: 1197

Powershell: Foreach not working?

So I have an issue with my foreach loop, and I cant figure out what I am doing wrong.

The following is an example of my code:

 $objectarray ##( So this variable contains a list of lists ie name + address) ##

 Foreach ($object in $objectarray.name){


$objectid = $objectarray.Where({$_.name -eq "$object"}).id
$objectaddress = $objectarray.Where({$_.name -eq "$object"}).address

$objectprint = "$objectid" + ": " + "$objectaddress"

$objectprint
return 0

}

Now the problem is $objectarray has multiple lists inside it each with its name, id, address etc

But it ONLY prints the FIRST one, and I get ONLY the first 0 as return...despite the fact there are many of them

Upvotes: 2

Views: 7432

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19664

You're parsing through your object in a weird way. Why don't you use the pipeline to make this a little easier on yourself?

$ObjectArray | % { "$($_.id): $($_.address)"; 0 }

Everything will be put onto the success/output pipeline this way and can be captured (for example, if you put $var = before the expression)

Upvotes: 5

Derek Lawrence
Derek Lawrence

Reputation: 1608

I think its because you are returning 0 inside your for loop. Should put that outside the loop.

Foreach ($object in $objectarray.name){

    $objectid = $objectarray.Where({$_.name -eq "$object"}).id
    $objectaddress = $objectarray.Where({$_.name -eq "$object"}).address

    $objectprint = "$objectid" + ": " + "$objectaddress"

    $objectprint
}
return 0

Upvotes: 1

Related Questions