1

I've got a plain text file called inputs.txt with the following content:

some_array = {
  "x" = "blabla1"
  "y" = "blabla2"
  "z" = "blabla3"
}
ip_addresses = {
  "x" = "1.2.3.4"
  "y" = "1.2.3.4"
  "z" = "1.2.3.4"
}
names = {
  "x" = "abc"
  "y" = "def"
  "z" = "ghi"
}

... and many more of the same type of arrays.

Now I need to use PowerShell to loop through the IP addresses in the object ip_addresses.

I'm not really coming any further than:

$file = Get-Content -Path ./inputs.txt

Which will return the entire file, but I just need the IP addresses. Prefereably comma seperated.

Is there an easy way to loop though this? It would have been easier if input.txt were json files but they're not unfortunately. This is the structure and it can't be changed.

Thanks in advance for any help!

JVGBI
  • 565
  • 1
  • 8
  • 26

3 Answers3

3

I would use switch for this:

$collectIPs = $false
$ipAddresses = switch -Regex -File 'D:\Test\inputs.txt' {
    '^ip_addresses\s*=' { $collectIPs = $true }
    '^}' {$collectIPs = $false }
    default {
        if ($collectIPs) { ($_ -split '=')[-1].Trim(' "') }
    }
}

$ipAddresses -join ', '

Output:

1.2.3.4, 1.2.3.4, 1.2.3.4
Theo
  • 57,719
  • 8
  • 24
  • 41
2

Sure with Json this would be easier.

$start = $false
$IPs = Get-Content -Path ./inputs.txt | ForEach-Object {
    if ($_ -match "}") {
        $start = $false
    }

    if ($start) {
        $arr = $_ -split "="
        $Name = ($arr[0] -replace '"', '').Trim()
        $Value = ($arr[1] -replace '"', '').Trim()
        New-Object -TypeName PSObject -Property @{Name=$Name; IP=$Value}
    }

    if ($_ -match "ip_addresses") {
        $start = $true
    }
}
Hazrelle
  • 758
  • 5
  • 9
1

You can use regex to extract all the IP Addresses from the file. All credits on the regex goes to this answer.

The following will give you an array, if you need them comma separated, -join ',' will do it.

$file = Get-Content ./inputs.txt -Raw

[regex]::Matches(
    $file,
    '\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
).Value

Note: the regex will only support valid IPv4 Addresses, something like 999.2.3.4 will not be matched.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37