Capture multiline, multi-group to Powershell variables

前端 未结 4 1688
忘了有多久
忘了有多久 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 08:06

    I know this doesn't directly answer your question. But rather than parsing the output of ipconfig with Regex. You could instead use Get-NetIPConfiguration to get a powershell object that is easier to deal with.

    PS> $ip = Get-NetIPConfiguration
    PS> $ip
    
    InterfaceAlias       : Ethernet
    InterfaceIndex       : 12
    InterfaceDescription : Intel(R) Ethernet Connection I217-LM
    NetProfile.Name      : xyz.com
    IPv4Address          : 10.20.102.162
    IPv6DefaultGateway   :
    IPv4DefaultGateway   : 10.20.102.1
    DNSServer            : 10.20.100.9
                           10.20.100.11
                           10.20.100.13
    
    PS> $ip.IPv4Address
    
    IPAddress         : 10.20.102.162
    InterfaceIndex    : 12
    InterfaceAlias    : Ethernet
    AddressFamily     : IPv4
    Type              : Unicast
    PrefixLength      : 23
    PrefixOrigin      : Dhcp
    SuffixOrigin      : Dhcp
    AddressState      : Preferred
    ValidLifetime     : 05:16:53
    PreferredLifetime : 05:16:53
    SkipAsSource      : False
    PolicyStore       : ActiveStore
    PSComputerName    :
    

    Thus you can do the following to get the values you are looking to acquire.

    $ip.InterfaceAlias
    $ip.InterfaceDescription
    $ip.IPv4Address.IPAddress
    

    To get the MAC the address you can use the Get-NetAdapter cmdlet.

    $adapter = Get-NetAdapter
    $adapter.MacAddress
    

    You can correlate the two pieces of information using the InterfaceIndex. Then return a hashtable that makes each accessible. The following creates an array of these combined objects.

    $combined = Get-NetIPConfiguration | ForEach-Object {
        $adapter = Get-NetAdapter -InterfaceIndex $_.InterfaceIndex
        @{ IP = $_; Adapter = $adapter }
    }
    

提交回复
热议问题