none
Take a particular IP from a txt file using powershell RRS feed

  • Question

  • Hi ,

    I am trying to trim a line from a txt file , so that I can collect only a specific IP address.The hostsraw.txt file contains below output. The output shows exactly same as screenshot like below, the IP address shows in second line of the output. I have even pasted the contents below.

    | df1b0d4d-e240-49b2-aa6f-6ea878f696eb | win101511bare-13-my_instance-v2deggvemd3g     | ACTIVE | 
    blcos10a-private=10.106.15.104, 10.110.20.77  |            |
    | 2a22a0d2-7924-4b1f-8852-11d73b250f18 | win101511bare-14-my_instance-v2deggvgmd3g     | ACTIVE | 
    blcos10a-private=10.106.15.105, 10.110.20.74  |            |

    I have used below two methords so that I can get only the IP address in below format to another ipaddress.txt .but output was not as I expected. Can anyone please help me correcting this ?

    10.110.20.77

    10.110.20.74


    These are the methords which I tried. Please help me to correct the script so that I can get the output as I expected.

    First methord

    ============

    $hostsraw = Get-Content C:\hostsraw.txt

    foreach ($line in $hostsraw) {

        $split1 = $line.trim("|")

        $split2 = $split1.Split(",")[1]

        echo $split2 >> C:\ipaddress.txt

        }

    When I used this methord, I am getting a pipe line along with IP address like below.

    10.110.20.77  |           

    10.110.20.74  |           

    Second Methord

    =============


    $hostsraw = Get-Content C:\hostsraw.txt

    foreach ($line in $hostsraw)  {

        $split1 = $line.Split(',')[1]

        $split2 = $split1.Split(' ')[1]

        $split2 >> C:\ipaddress.txt

        }

    When I used this methord, I am getting IP address  in repeated manner like below and also getting below errors too.

    10.110.20.74

    10.110.20.74

    10.110.20.77

    10.110.20.77

    10.110.20.74

    10.110.20.74

    10.110.20.74





    • Edited by Mcteer Thursday, March 23, 2017 8:45 AM
    Thursday, March 23, 2017 8:42 AM

Answers

  • $File = 'C:\hostsraw.txt'
    $LastIP = '(\d{1,3}(\.\d{1,3}){3})(?!.*(\d{1,3}(\.\d{1,3}){3}))'
    Select-String -Path $File -Pattern $LastIP | foreach {
        $_.Matches.Value
    } | Out-File C:\ipaddress.txt

    • Marked as answer by Mcteer Thursday, March 23, 2017 10:16 AM
    Thursday, March 23, 2017 9:23 AM

All replies