问题
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?
回答1:
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
回答2:
Using the .Net [IPAddress] Class:
([IPAddress]'172.13.23.34').GetAddressBytes()
172
13
23
34
来源:https://stackoverflow.com/questions/63710588/get-a-specific-octet-from-the-string-representation-of-an-ipv4-address