Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a line from a file in PowerShell

Tags:

powershell

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?

like image 319
sharsour Avatar asked Jul 29 '13 06:07

sharsour


People also ask

How do you read a new line in PowerShell?

Backtick (`) character is PowerShell line continuation character. It ensures the PowerShell script continue to a new line. To use line continuation character in PowerShell, type space at the end of code, use backtick ` and press enter to continue to new line.

How do I get the content of a file in PowerShell?

The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file or the content of a function. For files, the content is read one line at a time and returns a collection of objects, each of which represents a line of content.


2 Answers

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

like image 29
Filip Dobrovolný Avatar answered Oct 05 '22 11:10

Filip Dobrovolný


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" }
    }
}
like image 162
Keith Hill Avatar answered Oct 05 '22 11:10

Keith Hill