Powershell get ipv4 address into a variable

后端 未结 12 2599
长情又很酷
长情又很酷 2021-01-31 08:23

Is there an easy way in powershell 3.0 Windows 7 to get the local computer\'s ipv4 address into a variable?

12条回答
  •  情深已故
    2021-01-31 09:06

    I recently had the same issue. So I wrote a script to parse it from the ipconfig /all output. This script is easily modifiable to obtain any of the parameters of the interfaces and it works on Windows 7 also.

    1. Get output of IP config in LineNumber | Line format

    $ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)

    1. Get list of interfaces (+ last line of ipconfig output) in LineNumber | Line format

    $interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)

    1. Filter through the interfaces list for the specific interface you want

    $LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})

    1. Get the start and end line numbers of chosen interface from output

    $i = $interfaces.IndexOf($LAN)
    $start = $LAN.LineNumber
    $end = $interfaces[$i+1].LineNumber

    1. Pick the lines from start..end

    $LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}

    1. Get IP(v4) address field (returns null if no IPv4 address present)

    $LAN_IP = @($LAN | where {$_ -match 'IPv4.+:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'})
    $LAN_IP = &{If ($LAN_IP.Count -gt 0) {$Matches[1]} Else {$null}}

提交回复
热议问题