FOREACH LOOP AND ARRAY

Hi

 

I’m testing 3 different foreach loops with arrays. My First loop is popullating the correct oputput.

 

$add_server = @(‘Server one’, ‘Server two’, ‘Server three’)

foreach ($i in $add_server) {
Add-Content -Path “C:\Users\spate\Documents\SampleFile3.txt” -Value “$i”
}

Output

Server one

Server two

Server three

  1. Not correct output

$add_server | ForEach-Object (Add-Content -Path “C:\Users\spate\Documents\SampleFile2.txt” -Value “$i”)

Output

Server three

 

3)Not correct

$add_server2.ForEach({

Add-Content -Path “C:\Users\spate\Documents\SampleFile5.txt” -Value “$i”
})

 

output

Server three

Server three

Servver three

 

For the incorrect output’s I think I have to initalize the array to index[0]

But not sure what the issues is.

Thanks

For (2) & (3) it’s not correct because $i has no value.

You have to either assign that parameter a value or use the value the $_.

$add_server | ForEach-Object (Add-Content -Path “C:\Users\spate\Documents\SampleFile2.txt” -Value “$_”

or

$add_server | ForEach-Object ( $i = $_ ; Add-Content -Path “C:\Users\spate\Documents\SampleFile2.txt” -Value “$i”

 

Thanks Iain

$add_server | ForEach-Object (Add-Content -Path “C:\Users\spate\Documents\SampleFile9.txt” -Value “$_”)

know the file SampleFile9.txt is poppulating empty.

 

Hey Iian

I added $_ to the third script

$add_server2.ForEach({

Add-Content -Path “C:\Users\spate\Documents\SampleFile5.txt” -Value “$_”
})

 

AND THAT WORKS. I’M GOOD THANKS FOR YOUR HELP.