【问题标题】:Powershell get ipv4 address into a variablePowershell将ipv4地址放入变量中
【发布时间】:2014-12-03 17:14:38
【问题描述】:

powershell 3.0 Windows 7中是否有简单的方法将本地计算机的ipv4地址获取到变量中?

【问题讨论】:

    标签: windows powershell-3.0


    【解决方案1】:

    这是另一个解决方案:

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

    【讨论】:

    • 这很好用,但速度很慢,在我的笔记本电脑上运行需要 3981 毫秒 (i5-7th-gen/12GBRM)
    • not 在 Windows 7 上按 OP 要求工作。该 cmdlet 直到 Server 2012/Windows 8 才引入。
    • 在 Windows 10 上,这非常漂亮;第一次运行只花了大约一秒钟(并没有真正注意到它),之后就运行了,没有明显的延迟。 -- 它返回正确的 IP 地址。干得好。
    • Get-NetIPConfiguration 目前在 Linux 下的 Powershell Core 中不可用。
    • 我在 Windows 10 PS 5 上没有输出,但像这样拆分它可以工作:$i=Get-NetIPConfiguration|Where-Object{$_.ipv4defaultgateway -ne $null};$i.IPv4Address.ipaddress
    【解决方案2】:

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

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

    请注意,使用 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
    

    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
    

    【讨论】:

    • 有专门为示例/文档保留的 IP 地址(192.0.2.0/24、198.51.100.0/24,203.0.113.0/24)tools.ietf.org/html/rfc5737
    • $ip = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString
    • 您可以避免使用(hostname) 调用外部实用程序,方法是使用$env:COMPUTERNAME 环境变量,即Test-Connection $env:COMPUTERNAME -Count 1 | Select IPV4Address
    • 这很好用,谢谢。总结所有建议,这是最优雅的解决方案:$ipv4 = (Test-Connection -ComputerName $env:ComputerName -Count 1).IPV4Address.IPAddressToString 我在连接到有线网络的系统上对此进行了测试,结果显示 IPv4。未连接到任何网络时显示家庭 (127.0.0.1),连接到无线时显示 IPv4。
    • 如何获取wifi ipv4地址?它显示了我的 eth0 地址,在我的情况下,它是我的 wsl 网络。
    【解决方案3】:

    如果我使用机器名称,则可以。但是有点像 hack(因为我只是选择了我得到的 ipv4 地址的第一个值。)

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

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

    这也有效

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

    【讨论】:

    • 第二个表达式给了我以下错误:Program 'ipconfig.exe' failed to run: The directory name is invalidAt line:1 char:20 $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1] + ~~~~~~~~. At line:1 char:1 + $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed
    【解决方案4】:

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



    方法一:(这个方法最快,windows powershell和powershell core都可以)
    $ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress

    方法2:(此方法与方法1一样快,但不适用于powershell内核)
    $ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString

    方法3:(虽然最慢,但是windows powershell和powershell core都可以)
    $ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress

    【讨论】:

    • 这在某些系统上不可用:Get-NetIPConfiguration
    【解决方案5】:
    (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress
    

    【讨论】:

    • 这行得通。不过似乎不如例外答案优雅。
    • 这是不正确的。您可能还需要包含DHCPEnabled=True。此命令的输出与@Lucas (Get-NetIPConfiguration) 提供的不同。
    【解决方案6】:

    这是我最终使用的

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

    分解为

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

    【讨论】:

    • 丑,但效果很好,而且比接受的答案更快
    【解决方案7】:

    这一行给你IP地址:

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

    将其包含在变量中?

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

    【讨论】:

      【解决方案8】:

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

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

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

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

      【讨论】:

      • 请注意,这是非常危险的错误。它返回一些 IP 地址,但如果您有虚拟适配器(例如用于 VPN、Hyper-V、Docker 等),它可能不是外部可见的。
      • 这肯定不会在我的机器上返回正确的 IP 地址。
      【解决方案9】:

      tldr;

      我使用此命令将以太网网络适配器的 ip 地址放入一个名为 IP 的变量中。

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

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

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

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

      您会在命令提示符的输出中看到类似的表格:

      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)
      

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

      如前所述,我对 Ethernet 感兴趣。

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

      netsh interface ip show config name="Ethernet"

      这给了我们这个输出:

      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
      

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

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

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

      这给出了以下输出:

       IP Address:                           169.252.27.59
      

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

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

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

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

      for 命令的末尾,您可以指定一个命令来运行返回的内容。在这种情况下,我使用set 将值分配给名为IP 的环境变量。如果你愿意,你也可以只是回应价值或你喜欢的任何东西。

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

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

      【讨论】:

        【解决方案10】:

        我一直在寻找同样的东西并发现了这一点:

        $ip = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile | Select-Object -ExpandProperty InterfaceIndex) | Select-Object -ExpandProperty IPAddress
        

        这会过滤掉环回地址和我拥有的一些虚拟网络。

        【讨论】:

          【解决方案11】:

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

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

          【讨论】:

            【解决方案12】:
            # Patrick Burwell's Ping Script - Patrick.Burwell@Infosys.com #
            $Output= @() #sets an array
            $names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
            foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against 
              if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
              ){# If true then run...
               $Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
               Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
              }
              else{#If false then run...
                $Output+= "$name," #Fills the array with the #false response
                Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors 
              }
            }
            
            #$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
            #$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
            
            #If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments
            

            【讨论】:

            • 有人知道如何让第 7 行将 SINGLE LINE 写入数组吗? :)
            • $Output+= $Name,',',($IPV4.IPV4Address).IPAddressToString # 每个条目单独一行
            【解决方案13】:

            当我在 Powershell 3 中工作时,这里没有一个答案对我有用。它基于 Rob 的方法,但是当您有多个网络适配器时,此方法有效,它还使用捕获组正确选择 IP

            function GetIPConfig {      
                return ipconfig | select-string  ('(\s)+IPv4.+\s(?<IP>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(\s)*') -AllMatches | %{ $_.Matches } | % { $_.Groups["IP"]} | %{ $_.Value }
            }
            

            【讨论】:

              【解决方案14】:
              $ip = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile).InterfaceIndex).IPAddress
              

              function Get-LocalIP {
                  (
                      Get-NetIPAddress `
                          -AddressFamily IPv4 `
                          -InterfaceIndex $(
                              Get-NetConnectionProfile
                          ).InterfaceIndex
                  ).IPAddress
              }
              
              $ip = Get-LocalIP
              

              【讨论】:

                【解决方案15】:

                没有一个顶级 cmets 实际上是完全正确的,因为一台计算机可以有多个接口,而一个接口可以有多个 IP 地址。这里有一些答案在技术上是正确的,但使用“时髦”的方式来过滤掉众所周知的地址(如 APIPA、localhost 等),而即使 Powershell 3.0 也有使用 PrefixOrigin 的原生方式。

                $IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress
                

                【讨论】:

                  【解决方案16】:

                  我最近遇到了同样的问题。所以我写了一个脚本来从ipconfig /all 输出中解析它。这个脚本很容易修改以获得接口的任何参数,它也可以在 Windows 7 上运行。

                  1. LineNumber | Line 格式获取 IP 配置的输出

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

                  1. LineNumber | Line 格式获取接口列表(+ipconfig 输出的最后一行)

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

                  1. 通过接口列表过滤您想要的特定接口

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

                  1. 从输出中获取所选接口的开始和结束行号

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

                  1. start..end中选择行

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

                  1. 获取 IP(v4) 地址字段(如果不存在 IPv4 地址,则返回 null)

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

                  【讨论】:

                    【解决方案17】:
                    $a = ipconfig
                    $result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""
                    

                    还要检查 ipconfig 的哪个索引具有 IPv4 地址

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2020-10-30
                      • 1970-01-01
                      • 2011-08-19
                      • 1970-01-01
                      • 2011-02-16
                      • 2011-01-04
                      • 2016-10-17
                      相关资源
                      最近更新 更多