In Powershell Why might a foreach-object loop not let you retrieve individual values from an array?

770 views Asked by At

Note the following output. $Names is an array with two values. $Machinename is an array with two values.

Their positional values within the array are retrieved accurately outside of a foreach loop. When fetched within a foreach loop the value requested for the first position in the array i.e. $Names[0] ignores the positional call of [0]..... I need to be able to retrieve that value by itself..... Ultimately I will need to interate through each value to input to a command...

PS C:\Users\lab> $Names

john
jeff
PS C:\Users\lab> $Names[0]

john
PS C:\Users\lab> $Names[1]

jeff
PS C:\Users\lab> $Machinename

dev1
dev2
PS C:\Users\htlab> $Machinename | ForEach-Object  { Write-Output "$Names[0]"}

john jeff[0]
john jeff[0]

Sample Script:

$Names = 'john', 'jeff'
$machinename = 'dev1', 'dev2'
$Machinename | ForEach-Object  {Write-Output "$Names[0]"}
2

There are 2 answers

1
Enigmativity On

You're not evaluating the array. By writing "$Names[0]" it is the equivalent of $Names + "[0]".

You need to nest the evaluation inside $(...).

Try this:

$Machinename | ForEach-Object  {Write-Output "$($Names[0])"}

That gives me:

john
john

Equally, as pointed out in the comments, this works too:

$Machinename | ForEach-Object  {Write-Output $Names[0]}
3
Brnsn On

You could try something like this, as it seemed to work for me, unless thats not what you're asking,

for (($i = 0); $i -lt $names.Count; $i++)
{
 $Names[$i] + ":" + $Machinename[$i]
}

Output:

John:dev1
Jeff:dev2