|
| 1 | +class IPConfig { |
| 2 | + # The interface name |
| 3 | + [string] $InterfaceName |
| 4 | + |
| 5 | + # The interface description |
| 6 | + [string] $Description |
| 7 | + |
| 8 | + # The interface status |
| 9 | + [System.Net.NetworkInformation.OperationalStatus] $Status |
| 10 | + |
| 11 | + # The address family |
| 12 | + [string] $AddressFamily |
| 13 | + |
| 14 | + # The IP address |
| 15 | + [string] $IPAddress |
| 16 | + |
| 17 | + # The prefix length |
| 18 | + [int] $PrefixLength |
| 19 | + |
| 20 | + # The subnet mask |
| 21 | + [string] $SubnetMask |
| 22 | + |
| 23 | + # The gateway |
| 24 | + [string] $Gateway |
| 25 | + |
| 26 | + # The DNS servers |
| 27 | + [string] $DNSServers |
| 28 | + |
| 29 | + IPConfig( |
| 30 | + [System.Net.NetworkInformation.NetworkInterface] $Interface, |
| 31 | + [System.Net.NetworkInformation.UnicastIPAddressInformation] $AddressInformation, |
| 32 | + [System.Net.NetworkInformation.IPInterfaceProperties] $InterfaceProperties |
| 33 | + ) { |
| 34 | + $this.InterfaceName = $Interface.Name |
| 35 | + $this.Description = $Interface.Description |
| 36 | + $this.Status = $Interface.OperationalStatus |
| 37 | + switch ($AddressInformation.Address.AddressFamily) { |
| 38 | + ([System.Net.Sockets.AddressFamily]::InterNetwork) { $this.AddressFamily = 'IPv4'; break } |
| 39 | + ([System.Net.Sockets.AddressFamily]::InterNetworkV6) { $this.AddressFamily = 'IPv6'; break } |
| 40 | + default { $this.AddressFamily = $AddressInformation.Address.AddressFamily.ToString() } |
| 41 | + } |
| 42 | + $this.IPAddress = $AddressInformation.Address.IPAddressToString |
| 43 | + $this.PrefixLength = $AddressInformation.PrefixLength |
| 44 | + |
| 45 | + if ($AddressInformation.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) { |
| 46 | + $this.SubnetMask = [IPConfig]::ConvertPrefixToMask($AddressInformation.PrefixLength) |
| 47 | + } else { |
| 48 | + # IPv6 masks are represented by prefix length |
| 49 | + $this.SubnetMask = $null |
| 50 | + } |
| 51 | + |
| 52 | + $this.Gateway = ($InterfaceProperties.GatewayAddresses | ForEach-Object { $_.Address.IPAddressToString }) -join ', ' |
| 53 | + $this.DNSServers = ($InterfaceProperties.DnsAddresses | ForEach-Object { $_.IPAddressToString }) -join ', ' |
| 54 | + } |
| 55 | + |
| 56 | + hidden static [string] ConvertPrefixToMask([int] $prefixLength) { |
| 57 | + if ($prefixLength -le 0) { return '0.0.0.0' } |
| 58 | + if ($prefixLength -ge 32) { return '255.255.255.255' } |
| 59 | + |
| 60 | + [int[]] $octets = 0, 0, 0, 0 |
| 61 | + $bits = $prefixLength |
| 62 | + for ($i = 0; $i -lt 4; $i++) { |
| 63 | + $take = [Math]::Min(8, $bits) |
| 64 | + if ($take -le 0) { |
| 65 | + $octets[$i] = 0 |
| 66 | + } else { |
| 67 | + $octets[$i] = 255 - ([math]::Pow(2, (8 - $take)) - 1) |
| 68 | + } |
| 69 | + $bits -= $take |
| 70 | + } |
| 71 | + return ($octets -join '.') |
| 72 | + } |
| 73 | +} |
0 commit comments