windows Powershell 获取 ipv4 地址到一个变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27277701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:51:40  来源:igfitidea点击:

Powershell get ipv4 address into a variable

windowspowershell-3.0

提问by developer747

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

powershell 3.0 Windows 7 中是否有一种简单的方法可以将本地计算机的 ipv4 地址转换为变量?

回答by Lucas

Here is another solution:

这是另一个解决方案:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

回答by Jana Sattainathan

How about this? (not my real IP Address!)

这个怎么样?(不是我的真实 IP 地址!)

PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address                                                  
-----------
192.0.2.0

Note that using localhost would just return and IP of 127.0.0.1

请注意,使用 localhost 只会返回 127.0.0.1 的 IP

PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address                                                             
-----------                                                  
127.0.0.1

The IP Address object has to be expanded out to get the address string

必须扩展 IP 地址对象才能获取地址字符串

PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select -ExpandProperty IPV4Address 

PS C:\> $ipV4

Address            : 556228818
AddressFamily      : InterNetwork
ScopeId            : 
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 192.0.2.0


PS C:\> $ipV4.IPAddressToString
192.0.2.0

回答by developer747

If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)

如果我使用机器名称,这有效。但有点像黑客(因为我只是选择我得到的 ipv4 地址的第一个值。)

$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"}   |  select-object IPAddressToString)[0].IPAddressToString

Note that you have to replace the value PasteMachineNameHerein the above expression

请注意,您必须替换上面表达式中的值PasteMachineNameHere

This works too

这也有效

$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

回答by rob

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.
  • 执行 ipconfig 命令 - 获取所有网络接口信息
  • 使用带有正则表达式的 powershell 的 where 过滤器
  • 正则表达式查找带有“IPv4”的行和一组 4 个块,每个块由 1-3 个数字以句点分隔,即 v4 IP 地址
  • 通过将其管道化为 null 来忽略输出
  • 最后得到正则表达式中括号定义的第一个匹配组。
  • 在 $ipaddress 中捕获该输出以供以后使用。

回答by Nick Ali

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DefaultIPGateway -ne $null}).IPAddress | select-object -first 1

回答by icey

This one liner gives you the IP address:

这一班轮为您提供 IP 地址:

(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

Include it in a Variable?

将其包含在变量中?

$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

回答by Nicholas Leader

Another variant using $envenvironment variable to grab hostname:

另一个使用$env环境变量获取主机名的变体:

Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address

or if you just want the IP address returned without the property header

或者如果您只想返回没有属性标头的 IP 地址

(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring

回答by Dellius Alexander

Here are three methods using windows powershelland/or powershell core, listed from fastest to slowest. You can assign it to a variable of your choosing.

以下是使用windows powershell和/或powershell core 的三种方法,从最快到最慢列出。您可以将其分配给您选择的变量。






方法一:(这个方法是最快的,在windows powershell和powershell core下都可以用)


$ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress





方法二:(这个方法和方法一一样快,但是对powershell core不适用)


$ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString





方法三:(虽然最慢,但是在windows powershell和powershell core上都可以使用)


$ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress

回答by Joshua Dyck

tldr;

tldr;

I used this command to get the ip address of my Ethernet network adapter into a variable called IP.

我使用这个命令将我的以太网网络适配器的 ip 地址获取到一个名为 IP 的变量中。

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

For those who are curious to know what all that means, read on

对于那些想知道这一切意味着什么的人,请继续阅读

Most commands using ipconfigfor example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.

ipconfig例如,使用的大多数命令只是打印出您所有的 IP 地址,而我需要一个特定的地址,在我的情况下是用于我的以太网网络适配器。

You can see your list of network adapters by using the netsh interface ipv4 show interfacescommand. Most people need Wi-Fi or Ethernet.

您可以使用该netsh interface ipv4 show interfaces命令查看网络适配器列表。大多数人需要 Wi-Fi 或以太网。

You'll see a table like so in the output to the command prompt:

您将在命令提示符的输出中看到这样的表:

Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          75  4294967295  connected     Loopback Pseudo-Interface 1
 15          25        1500  connected     Ethernet
 17        5000        1500  connected     vEthernet (Default Switch)
 32          15        1500  connected     vEthernet (DockerNAT)

In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).

在名称列中,您应该找到所需的网络适配器(即以太网、Wi-Fi 等)。

As mentioned, I was interested in Ethernetin my case.

如前所述,我对Ethernet我的案例很感兴趣。

To get the IP for that adapter we can use the netsh command:

要获取该适配器的 IP,我们可以使用 netsh 命令:

netsh interface ip show config name="Ethernet"

netsh interface ip show config name="Ethernet"

This gives us this output:

这给了我们这个输出:

Configuration for interface "Ethernet"
    DHCP enabled:                         Yes
    IP Address:                           169.252.27.59
    Subnet Prefix:                        169.252.0.0/16 (mask 255.255.0.0)
    InterfaceMetric:                      25
    DNS servers configured through DHCP:  None
    Register with which suffix:           Primary only
    WINS servers configured through DHCP: None

(I faked the actual IP number above for security reasons )

(出于安全原因,我伪造了上面的实际 IP 号码)

I can further specify which line I want using the findstrcommand in the ms-dos command prompt. Here I want the line containing the string IP Address.

我可以使用findstrms-dos 命令提示符中的命令进一步指定我想要的行。这里我想要包含字符串的行IP Address

netsh interface ip show config name="Ethernet" | findstr "IP Address"

This gives the following output:

这给出了以下输出:

 IP Address:                           169.252.27.59

I can then use the forcommand that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.

然后,我可以使用for允许我解析文件(或本例中的多行字符串)的命令,并根据分隔符和我感兴趣的项目编号拆分字符串的内容。

Note that I am looking for the third item (tokens=3) and that I am using the space character and :as my delimiters (delims=:).

请注意,我正在寻找第三个项目 (tokens=3),并且我正在使用空格字符和:作为我的分隔符 ( delims=:)。

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the |and =using a ^

循环中的每个值或标记都作为变量 %i 打印出来,但我只对第三个“标记”或项目感兴趣(因此tokens=3)。请注意,我必须逃脱|=使用^

At the end of the forcommand you can specify a command to run with the content that is returned. In this case I am using setto assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.

for命令的末尾,您可以指定要使用返回的内容运行的命令。在这种情况下,我使用set将值分配给名为IP. 如果您愿意,您也可以只回显该值或您喜欢的任何内容。

With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?

有了它,您将获得一个环境变量,其中您的首选网络适配器的 IP 地址分配给环境变量。很整洁吧?

If you have any ideas for improving please leave a comment.

如果您有任何改进的想法,请发表评论。

回答by Guardial

To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.*for example.

获取设备的 IPv4 地址,并过滤以仅获取与您的方案匹配的地址(即忽略和 APIPA 地址或 LocalHost 地址)。例如,您可以说抓取地址匹配192.168.200.*

$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress