需要在字符串下获取子字符串

问题描述 投票:0回答:3

我需要获取一个特定字符串下的String。

$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}}

例如,我需要在无线LAN适配器本地连接* 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 . . . . . . . . . :
powershell powershell-v2.0 powershell-v3.0
3个回答
1
投票

就像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

0
投票

如果绑定并确定将其解析为文本,则可以使用正则表达式来执行此操作。

$a = ipconfig | Select-String 'IPv4.*\s(?<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3})'
$a.matches[0].groups["ip"].value

10.11.12.13

这使用Select-String的正则表达式匹配来查找匹配作为命名组,将它们保存为matchinfo对象,然后输出到屏幕。正则表达式详细信息可以找到here


0
投票

有一种方法可以将字符串合并为一个,然后使用正则表达式将其拆分。

$s = "Wireless LAN adapter Local Area Connection* 13"
$k = "IPv4 Address"

$part = (ipconfig) -join "`n" -split "(?<=\n)(?=\S)" | Where-Object { $_.StartsWith($s) }

$part.Split("`n") |
    Where-Object { $_.TrimStart().StartsWith($k) } |
    ForEach-Object { $_.Split(":", 2)[1].Trim() }
© www.soinside.com 2019 - 2024. All rights reserved.