Open2

PowerShell の便利な関数とか

Junya Yamaguchi (@openjny)Junya Yamaguchi (@openjny)

自分のグローバル IP アドレスを確認する

function Get-MyIPAddress {
    param (
        [switch]$IPv6
    )

    $Ipv6Fetchers = @(
        { (Resolve-DnsName "whoami.akamai.net" -Type AAAA).IPAddress },
        { (Resolve-DnsName "myip.opendns.com" -Server "resolver1.ipv6-sandbox.opendns.com" -Type AAAA).IPAddress }
    )

    $Ipv4Fetchers = @(
        { (Resolve-DnsName "whoami.akamai.net" -Type A).IPAddress },
        { (Resolve-DnsName "myip.opendns.com" -Server "resolver1.opendns.com" -Type A).IPAddress }
    )

    $fetchers = if ($IPv6) { $Ipv6Fetchers } else { $Ipv4Fetchers }
    $pattern = if ($IPv6) { '([a-f0-9]{1,4}:){7}[a-f0-9]{1,4}' } else { '(\d{1,3}\.){3}\d{1,3}' }
    foreach ($fetcher in $fetchers) {
        try {
            $ip = & $fetcher
            if ($ip -match "^$pattern$") {
                return $ip
            }
        }
        catch {
            continue
        }
    }

    return $null
}
Junya Yamaguchi (@openjny)Junya Yamaguchi (@openjny)

IP アドレスを含む CIDR を計算する

function Get-CidrBlockOf {
    # IP アドレスを含む CIDR ブロックを計算して返す
    #
    # Get-CidrBlockOf -IpAddress "192.168.1.13" -PrefixLength 24 -> "192.168.1.0/24"
    # Get-CidrBlockOf -IpAddress "192.168.1.13" -PrefixLength 29 -> "192.168.1.8/30"
    param (
        [string]$IpAddress,
        [int]$PrefixLength
    )
    if ([string]::IsNullOrEmpty($IpAddress) -or $PrefixLength -lt 1 -or $PrefixLength -gt 32) {
        return $null
    }
    if ($IpAddress -notmatch '^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$') {
        return $null
    }
    $parts = $IpAddress.Split('.') | ForEach-Object { [byte]([int]$_) }
    $ipInt = ([uint32]$parts[0] -shl 24) -bor ([uint32]$parts[1] -shl 16) -bor ([uint32]$parts[2] -shl 8) -bor ([uint32]$parts[3])
    if ($PrefixLength -eq 0) { return "0.0.0.0/0" }
    if ($PrefixLength -eq 32) {
        $mask = [uint32]0xFFFFFFFF
    }
    else {
        $ones = ([uint64]1 -shl $PrefixLength) - 1  # up to 32 bits of ones
        $mask = [uint32]($ones -shl (32 - $PrefixLength))
    }
    $network = $ipInt -band $mask
    $oct1 = [int](($network -shr 24) -band 0xFF)
    $oct2 = [int](($network -shr 16) -band 0xFF)
    $oct3 = [int](($network -shr 8) -band 0xFF)
    $oct4 = [int]($network -band 0xFF)
    return "$oct1.$oct2.$oct3.$oct4/$PrefixLength"
}