从IPv4地址的字符串表示形式获取特定的八位位组 [英] Get a specific octet from the string representation of an IPv4 address

查看:61
本文介绍了从IPv4地址的字符串表示形式获取特定的八位位组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为$Ip的变量.该变量在内部具有类似于"172.13.23.34"的IP.我想获取第三个八位位组或172.13之间的下一个字符.和.34(在这种情况下为字符串数字23),并存储在另一个变量中,以使用以下命令设置VLANID.

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

如何获取此特定信息?

推荐答案

While -split, the regex-based string-splitting operator, or the literal-substring-based Split() method are the proper tools for splitting a string into tokens by separators in general, there's an easier solution in your case:

# 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地址的八位字节,如下所示:

The [version] (System.Version) type, intended for version numbers, understands 4-component numbers separated by ., which look like IPv4 addresses. The properties of such instances map onto the octets of an IPv4 address as follows:

  • .Major ...第一个八位位组(172)
  • .Minor ...第二个八位位组(13)
  • .Build ...第三个八位位组(23)
  • .Revision ...第四字节(34)
  • .Major ... 1st octet (172)
  • .Minor ... 2nd octet (13)
  • .Build ... 3rd octet (23)
  • .Revision ... 4th octet (34)

注意:

  • 如果需要所有个八位位组,请考虑 iRon的有用答案,其中正确使用[IPAddress]类型.

  • If you need all octets, consider iRon's helpful answer, which more properly uses the [IPAddress] type.

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

That said, [version] has one advantage over [IPAddress]: it implements the System.IComparable interface, which means that you compare IPv4 addresses; e.g.,
[version] '172.9.23.34' -lt [version] '172.13.23.34' is $true

这篇关于从IPv4地址的字符串表示形式获取特定的八位位组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆