Pulling Partial Line From Text File Into Variable

This topic contains 3 replies, has 4 voices, and was last updated by  Curtis Smith 2 weeks, 4 days ago.

  • Author
    Posts
  • #76135

    Jay
    Participant

    Hello,

    I've used this forum in the past to find a ton of answers but haven't had any luck finding what I'm trying to do so this is my first post. I'm OK with Powershell but no where near a heavy hitter.

    I have a text file that has some network information in it on different lines. I'm needing to pull the IP information from one specific line. The line I need looks like "First 3 Octets of Network Address=192.168.160."

    There are two parts to this:

    1.) I need to pull out just the "192.168.160." part of that line and put it into a variable.
    2.) I need to pull out just the "192.168.160." part of that line, increment the 3rd octet by 1 (making it .161) and put it into another variable.

    I've found bits and pieces of what I'm trying to do online but haven't had luck trying to combine it.

    Thanks,

    Jay

  • #76138

    Max
    Participant

    What about using $start = indexof("=") with substring($start+1,start+12), then you can split the IP by ., then assign the third member of the array to an int, which you an increase by one and then build a new variable with [0].[1].$int ?

  • #76144

    Tim Curwick
    Participant

    Jay,

    There a few different options depending on the expected consistency of the input data. Here is one way:

    $Line = Get-Content -path $FilePath | Where-Object { $_.StartsWith( 'First 3 Octets of Network Address' ) | Select-Object -First 1
    $ThreeOctets = $Line.Split( '=' )[-1]
    $NewOctet = [int]$ThreeOctets.Split( '.' )[2] + 1

  • #76195

    Curtis Smith
    Participant

    You can also use RegEx to do it pretty easily

    If('First 3 Octets of Network Address=192.168.160.' -match "(?'IP'(?'Begin'\d+\.\d+\.)(?'ThirdOct'\d+))"){
        $matches['IP']
        $matches['Begin']
        $matches['ThirdOct']
        [int]$matches['ThirdOct']+1
        $matches['Begin'] + [string]([int]$matches['ThirdOct']+1)
    }

    Results:

    192.168.160
    192.168.
    160
    161
    192.168.161

    Of course you don't have to output all the parts, you can just output the final result.

    PS C:\Windows\System32\WindowsPowerShell\v1.0> If('First 3 Octets of Network Address=192.168.160.' -match "(?'IP'(?'Begin'\d+\.\d+\.)(?'ThirdOct'\d+))"){
        $matches['Begin'] + [string]([int]$matches['ThirdOct']+1)
    }

    Results:

    192.168.161

You must be logged in to reply to this topic.