首页 > 解决方案 > 需要得到一个字符串下的子字符串

问题描述

我需要得到一个特定字符串下的字符串。

$string = 'Wireless LAN adapter Local Area Connection* 13' 
ipconfig | ForEach-Object{if($_ -match $string){Select-String -AllMatches 'IPv4 Address' | Out-File C:\Temp\Avi\found.txt}}

例如,我需要在 Wireless LAN adapter Local Area Connection* 13 下获取 IPv4 地址。

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::34f2:d41c:3889:452e%21
   IPv4 Address. . . . . . . . . . . : 172.20.10.2
   Subnet Mask . . . . . . . . . . . : 255.255.255.240
   Default Gateway . . . . . . . . . : 172.20.10.1

Wireless LAN adapter Local Area Connection* 13:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::b946:1464:9876:9e03%29
   IPv4 Address. . . . . . . . . . . : 192.168.137.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

标签: powershellpowershell-2.0powershell-3.0

解决方案


就像 Lee 所暗示的那样,您真的不想为此使用 ipconfig ,使用Powershell 本机命令要容易得多。例如。要获取接口“Ethernet 8”和“Ethernet 10”的 IPv4 地址,您可以使用以下内容:

$NetworkInterfaces = @(
    "Ethernet 10"
    "Ethernet 8"
)
foreach ($Interface in $NetworkInterfaces) {
    Get-NetIPAddress -InterfaceAlias $Interface -AddressFamily IPv4 |
        Select-Object InterfaceAlias,IPAddress 
}

在我的情况下返回这个:

InterfaceAlias IPAddress
-------------- ---------
Ethernet 10    169.254.157.233
Ethernet 8     169.254.10.64

推荐阅读