Djair Silva
Djair Silva

Reputation: 31

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?

Upvotes: 3

Views: 1787

Answers (2)

mklement0
mklement0

Reputation: 437090

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

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 ... 1st octet (172)
  • .Minor ... 2nd octet (13)
  • .Build ... 3rd octet (23)
  • .Revision ... 4th octet (34)

Note:

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

  • 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

Upvotes: 4

iRon
iRon

Reputation: 23623

Using the .Net [IPAddress] Class:

([IPAddress]'172.13.23.34').GetAddressBytes()
172
13
23
34

Upvotes: 2

Related Questions