Parsing text into object

The result from a DOS command is text lines which does not have a "real" column. If you want to analyze the result, you must parse the text yourself.

For example, we want to find out the IP to physical addresses, we use the following command:

    arp -a

The result looks like this:

Interface: 192.168.1.100 --- 0x5
  Internet Address      Physical Address      Type
  192.168.1.1           18-31-bf-53-7a-24     dynamic  
  192.168.1.255         ff-ff-ff-ff-ff-ff     static   
  224.0.0.22            01-00-5e-00-00-16     static   
  224.0.0.251           01-00-5e-00-00-fb     static   
  224.0.0.252           01-00-5e-00-00-fc     static   
  239.255.255.250       01-00-5e-7f-ff-fa     static   
  255.255.255.255       ff-ff-ff-ff-ff-ff     static 

To parse this result, we will run the following Powershell script:

class myObject {
    [string]$ip
    [string]$addr
    [string]$type
}

$l = (arp -a)

$inPreamble = $true

switch -Regex ($l) {

    # skip the header
    {$inPreamble -and $_ -match 'Internet Address'} { $inPreamble = $false; continue }

    # parse the item lines with pattern:
    # - spaces
    # - ip (non spaces)
    # - addr (non spaces)
    # - type (non spaces)

    "^\s+(?<ip>\S+)\s+(?<addr>\S+)\s+(?<type>\S+)" {
       
        [myObject] @{
            ip = $matches.ip
            addr = $matches.addr
            type = $matches.type
        }

        continue
    }
   
}

# reference: https://devblogs.microsoft.com/powershell/parsing-text-with-powershell-2-3/


Comments

Popular posts from this blog

Scheduled task in Windows Task Scheduler - part 3

Create scheduled task in Windows Task Scheduler

Get all website entries in IIS