Home > Back-end >  Get object from a file using Powershell
Get object from a file using Powershell

Time:11-30

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!

CodePudding user response:

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
    }
}

CodePudding user response:

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

CodePudding user response:

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.

  • Related