NetworkHelper/Public/ConvertTo-DottedDecimalIp.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Function ConvertTo-DottedDecimalIP
{
    
    
    [CmdLetBinding()]
    Param (
        [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
        [String]$IPAddress
    )
    
    process
    {
        switch -RegEx ($IPAddress)
        {
            '([01]{8}\.){3}[01]{8}'
            {
                return [String]::Join('.', $($IPAddress.Split('.') | ForEach-Object -Process {
                            [Convert]::ToUInt32($_, 2)
                        }
                    ))
            }
            {$_ -as [Uint32]}
            {
                $IPAddress = [UInt32]$IPAddress
                $dottedIP = $(For ($i = 3; $i -gt -1; $i--)
                    {
                        $remainder = $IPAddress % [Math]::Pow(256, $i)
                        ($IPAddress - $remainder) / [Math]::Pow(256, $i)
                        $IPAddress = $remainder
                    }
                )
                
                return [String]::Join('.', $dottedIP)
            }
            default
            {
                throw 'Cannot convert this format'
            }
        }
    }
}