Search code examples
powershellgetcontent

Powershell Get-Content specific content inside text


I receive a text file with a multiple lists like shown below (edit: more accurate example dataset included)

# SYSTEM X
# SINGULAR
192.168.1.3
# SUB-SYSTEM V
192.168.1.4
192.168.1.5
192.168.1.6
# SYSTEM Y
# MANDATORY
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.7
192.168.1.8
192.168.1.9

Each "SYSTEM comment" means its a new set after it. I want to read each block of content separately so each set should be assigned to an object discarding the embedded comments. I just need the IPs. Something like:

$ipX = get-content -path [file.txt] [set X]
$ipY = get-content -path [file.txt] [set Y]
$ipZ = get-content -path [file.txt] [set Z]

But I'm not sure how to actually assign these sets separately. Help please.


Solution

  • Here's one possible solution. The result will be a hashtable, each key containing any array of ips for the set:

    $result = @{}
    get-content file.txt | foreach {
        if ($_ -match "#\s*SET\s+(\w+)") {
            $result[($key = $matches.1)] = @()
        }
        elseif ($_ -notlike "#*") {
            $result[$key] += $_
        }
    }
    

    Contents of $result:

    Name                           Value                                                                                                                                                                                  
    ----                           -----                                                                                                                                                                                  
    Y                              {[ip], [ip], [more ips]}                                                                                                                                                               
    Z                              {[ip], [ip], [more ips]}                                                                                                                                                               
    X                              {[ip], [ip], [more ips]}