9

I am novice to the PowerShell scripting. I am looking to fulfill one of my requirement.

I have one hosts file which is having multiple host names and IP addresses. Below is the example of the input file.

127.0.0.1 Host1 Host2 Host3

127.0.0.2 Host4 Host5 Host6

I want to read each line and ping for the first host (Host1), then the second host (Host2) and then the third host (Host3).

While pinging each host name, I need to check the ping response IP address for that host and match it back with the IP address mentioned in the input file. Below is the snippet of code with which am trying to read the file in the above format, but it is not working in that way.

 $lines = Get-Content myfile.txt
    $lines |
     ForEach-Object{
         Test-Connection  $_.Split(' ')[1]
     }

Can anyone give me any advice or whip something in a PowerShell script for me?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sharsour
  • 119
  • 2
  • 2
  • 4

2 Answers2

15

Try the following approach. It should be close.

$lines = Get-Content myfile.txt | Where {$_ -notmatch '^\s+$'} 
foreach ($line in $lines) {
    $fields = $line -split '\s+'
    $ip = $fields[0]
    $hosts = $fields[1..3]
    foreach ($h in $hosts) {
        $hostIP = (Test-Connection $h -Count 1).IPV4Address.ToString()
        if ($hostIP -ne $ip) { "Invalid host IP $hostIP for host $h" }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • `Test-Connection` will use the IP from the host file since its first in the resolution order so I think it will always match whats in the host file. – Andy Arismendi Jul 29 '13 at 07:11
  • Thanks Keith, I tried running your script but it is giving below issues. Cannot overwrite variable Host because it is read-only or constant. At D:\CEP\TestScript.ps1:6 char:12 + foreach <<<< ($host in $hosts) { + CategoryInfo : WriteError: (Host:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritable – sharsour Jul 29 '13 at 07:39
  • @sharsour doh, used the name of a built-in variable. I fixed that. – Keith Hill Jul 29 '13 at 15:05
  • @AndyArismendi In that case, you could always clear out the hosts settings file, run the script and then restore the entries to the hosts file. – Keith Hill Jul 29 '13 at 15:53
2

I'm never seen anything from PowerShell, but I mean it can be helpful for you. Something like the following:

foreach ($line in $lines.Split('\r\n')){
    Test-Connection  $line.Split(' ')[1]
}

http://en.wikipedia.org/wiki/Newline

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Filip Dobrovolný
  • 11,483
  • 3
  • 15
  • 16
  • Thanks brnopcman, But it is giving error as Split function is contained in System.Object[] only. It cannot be used for for-each. – sharsour Jul 29 '13 at 06:40
  • ok, I'm find something else: http://stackoverflow.com/questions/4192072/how-to-process-a-file-in-powershell-line-by-line-as-a-stream – Filip Dobrovolný Jul 29 '13 at 06:55