Chris Herzog
Chris Herzog

Reputation: 29

Powershell loop iteration

#gets the file location/file name of the IP address
Param($addr)
$file = Get-Content $addr
$i = 0
while ($i -ne $file.Count) {
  Write-Host $file
  $i++
}

Output:

8.8.8.8 127.0.0.1 208.67.222.222
8.8.8.8 127.0.0.1 208.67.222.222
8.8.8.8 127.0.0.1 208.67.222.222

File content:

8.8.8.8
127.0.0.1
208.67.222.222

I only want it to iterate and print out one line, not all three lines on a single line 3 times. I need this so I can run a ping command on each address.

Upvotes: 0

Views: 416

Answers (2)

Esperento57
Esperento57

Reputation: 17492

you can use $_ as file row with pipe like this :

Param($addr)
Get-Content $addr | foreach{ $_ }


#short version
Param($addr)
gc $addr | %{ $_ }

Upvotes: 0

Moerwald
Moerwald

Reputation: 11304

You've to use the index operator [] on $file.

#gets the file location/file name of the IP address
param($addr)
$file = get-content $addr
$i=0 
while ($i -ne $file.count){
   write-host $file[i]
   $i++
}

Upvotes: 1

Related Questions