首页 > 解决方案 > Get a specific octet from the string representation of an IPv4 address

问题描述

I have a variable named $Ip. This variable has an IP inside like "172.13.23.34". I would like to get the 3rd octet or the next character between 172.13. and .34 which is a string number 23 in this case and store in another variable to set up a VLANID with the command below.

$Ip = 172.13.23.34
$VLANID = ?
Set-Netadapter -Name "Ethernet" -VlanID $VLANID

How can I get this specific information?

标签: stringpowershellip-address

解决方案


虽然-split,基于正则表达式的字符串拆分运算符或基于文字子字符串的方法通常是通过分隔符将字符串拆分为标记的适当工具,但在您的情况下有一个更简单的解决方案:Split()

# Trick: [version] splits the string into its numerical components.
#        The .Build property value corresponds to the 3rd octet.
PS> ([version] '172.13.23.34').Build
23

( [version])System.Version类型,用于版本号,理解由 4 分隔的数字.看起来像 IPv4 地址。此类实例的属性映射到 IPv4 地址的八位字节,如下所示:

  • .Major... 第一个八位字节 ( 172)
  • .Minor... 第二个八位字节 ( 13)
  • .Build... 第 3 个八位字节 ( 23)
  • .Revision... 第 4 个八位字节 ( 34)

笔记:

  • 如果您需要所有八位字节,请考虑iRon 的有用答案,它更正确地使用了该[IPAddress]类型。

  • 也就是说,[version]它有一个优势[IPAddress]:它实现了System.IComparable接口,这意味着您可以比较IPv4 地址;例如,
    [version] '172.9.23.34' -lt [version] '172.13.23.34'$true


推荐阅读