Capture multiline, multi-group to Powershell variables

前端 未结 4 1623
忘了有多久
忘了有多久 2021-01-20 07:27

Ideally, I would like to create an object from ipconfig that allows us to drilldown to each adapter\'s attributes like this: $ip.$lan.$mac for the lan adapter\'s mac address

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 07:42

    Looking at the output of IPCONFIG /ALL, it looks like there are 3 different types of data being returned - the header section at the beginning and the an arbitrary number of sections for active and inactive adapters, each with a different format and set of data returned.

    Here is a set of regular expressions that can be used to parse each one, and capture the values presented:

    $Header_Regex = 
    @'
    (?m)Windows IP Configuration
    
       Host Name . . . . . . . . . . . . : (.*)
       Primary Dns Suffix  . . . . . . . : (.*)
       Node Type . . . . . . . . . . . . : (.*)
       IP Routing Enabled. . . . . . . . : (.*)
       WINS Proxy Enabled. . . . . . . . : (.*)
    
    '@
    
    
    $Active_Adapter_Regex  =
    @'
    (?m)(.+? adapter .+):
    
       Connection-specific DNS Suffix  . : (.*)
       Description . . . . . . . . . . . : (.*)
       Physical Address. . . . . . . . . : (.*)
       DHCP Enabled. . . . . . . . . . . : (.*)
       Autoconfiguration Enabled . . . . : (.*)
       Link-local IPv6 Address . . . . . : (.*) 
       IPv4 Address. . . . . . . . . . . : (.*)
       Subnet Mask . . . . . . . . . . . : (.*)
       Lease Obtained. . . . . . . . . . : (.*)
       Lease Expires . . . . . . . . . . : (.*)
       Default Gateway . . . . . . . . . : (.*)
       DHCP Server . . . . . . . . . . . : (.*)
       DHCPv6 IAID . . . . . . . . . . . : (.*)
       DHCPv6 Client DUID. . . . . . . . : (.*)
       DNS Servers . . . . . . . . . . . : ((?:.|\n)*)
       NetBIOS over Tcpip. . . . . . . . : (.*)
    '@
    
    $Inactive_Adapter_Regex = 
    @'
    (?m)(.+? adapter .+):
    
       Media State . . . . . . . . . . . : (.*)
       Connection-specific DNS Suffix  . : (.*)
       Description . . . . . . . . . . . : (.*)
       Physical Address. . . . . . . . . : (.*)
       DHCP Enabled. . . . . . . . . . . : (.*)
       Autoconfiguration Enabled . . . . : (.*)
    
    '@
    
    $Cmd_Output = (ipconfig /all | out-string) 
    
    $header = 
    if ($Cmd_Output -match $Header_Regex)
      {$matches}
    
    $Inactive_Adapters = 
    [regex]::Matches($Cmd_Output,$Inactive_Adapter_Regex) 
    
    $Active_Adapters =
    [regex]::Matches($Cmd_Output,$Active_Adapter_Regex) 
    

    chew on that a bit, and let me know if that's making any sense.

提交回复
热议问题