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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With