Powershell get ipv4 address into a variable

后端 未结 12 2326
长情又很酷
长情又很酷 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:15

    Here is what I ended up using

    $ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
    

    which breaks down as

    • execute ipconfig command - get all the network interface information
    • use powershell's where filter with a regular expression
    • regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
    • disregard the output by piping it to null
    • finally get the first matched group as defined by the brackets in the regular expression.
    • catch that output in $ipaddress for later use.

提交回复
热议问题