Skip to content

Instantly share code, notes, and snippets.

@paddy74
Created April 1, 2025 18:03
Show Gist options
  • Save paddy74/3bfb1b5baaa45e89611b0638dec82511 to your computer and use it in GitHub Desktop.
Save paddy74/3bfb1b5baaa45e89611b0638dec82511 to your computer and use it in GitHub Desktop.
find_netmask.ps1
function Convert-PrefixToNetmask {
param (
[Parameter(Mandatory = $true)]
[int]$PrefixLength
)
# Create a binary mask string with 1's for the prefix and pad with 0's
$binaryMask = ("1" * $PrefixLength).PadRight(32, "0")
$octets = @()
# Convert each 8-bit block to a decimal number
for ($i = 0; $i -lt 4; $i++) {
$octetBinary = $binaryMask.Substring($i * 8, 8)
$octets += [convert]::ToInt32($octetBinary, 2)
}
return $octets -join "."
}
# Example usage:
$interface = "Ethernet"
$ipConfig = Get-NetIPConfiguration -InterfaceAlias $interface
$prefixLength = $ipConfig.IPv4Address.PrefixLength
$netmask = Convert-PrefixToNetmask -PrefixLength $prefixLength
Write-Output "Prefix Length: $prefixLength"
Write-Output "Netmask: $netmask"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment