You can use the IPAddress class. Example:
[IPAddress] (([IPAddress] "192.168.100.45").Address -band ([IPAddress] "255.255.255.0").Address)
This will output an IPAddress object containing the IP address 192.168.100.0.
To convert a bit count to an equivalent bitmask string, you can use a function such as:
function ConvertTo-IPv4MaskString {
param(
[Parameter(Mandatory = $true)]
[ValidateRange(0, 32)]
[Int] $MaskBits
)
$mask = ([Math]::Pow(2, $MaskBits) - 1) * [Math]::Pow(2, (32 - $MaskBits))
$bytes = [BitConverter]::GetBytes([UInt32] $mask)
(($bytes.Count - 1)..0 | ForEach-Object { [String] $bytes[$_] }) -join "."
}
Using this function, you could write:
[IPAddress] (([IPAddress] "192.168.100.45").Address -band ([IPAddress] (ConvertTo-IPv4MaskString 24)).Address)
This outputs an IPAddress object containing the IP address 192.168.100.0.
A couple of other functions might be useful:
function Test-IPv4MaskString {
param(
[Parameter(Mandatory = $true)]
[String] $MaskString
)
$validBytes = '0|128|192|224|240|248|252|254|255'
$MaskString -match `
('^((({0})\.0\.0\.0)|' -f $validBytes) +
('(255\.({0})\.0\.0)|' -f $validBytes) +
('(255\.255\.({0})\.0)|' -f $validBytes) +
('(255\.255\.255\.({0})))$' -f $validBytes)
}
function ConvertTo-IPv4MaskBits {
param(
[parameter(Mandatory = $true)]
[ValidateScript({Test-IPv4MaskString $_})]
[String] $MaskString
)
$mask = ([IPAddress] $MaskString).Address
for ( $bitCount = 0; $mask -ne 0; $bitCount++ ) {
$mask = $mask -band ($mask - 1)
}
$bitCount
}
ConvertTo-IPv4MaskBits is the inverse of ConvertTo-IPv4MaskString and uses Test-IPv4MaskString to validate whether the mask is a valid IPv4 mask.
There's a bit more detail available in an article I wrote a while back:
IT Pro Today - Working with IPv4 Addresses in PowerShell
$IPAddr, which is192.168.100.45, with its CIDR SM of/24, into its corresponding SN value of192.168.100.0, and pass it on to another variable to be used for another part of my script. - Jeenetshoutput? Say,netsh interface ip show config 'Ethernet'? - vonPryznetshone-liner, and then directly pass that value to a variable for another command, then by all means that's worth a try. - Jee