-
Notifications
You must be signed in to change notification settings - Fork 214
/
IPUtils.ps1
66 lines (63 loc) · 1.9 KB
/
IPUtils.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Some ip related utility functions
# Gets the ip location info from ipgeolocationapi.com
function Get-IPLocationInfo
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="IPText", Mandatory=$true)]
[String]$IpAddress,
[Parameter(ParameterSetName="Host", Mandatory=$true)]
[String]$HostName,
[Parameter(ParameterSetName="IPBytes", Mandatory=$true)]
[byte[]]$IpBytes,
[switch]$Short
)
Process
{
if($IpBytes -ne $null)
{
if($IpBytes.Length -ne 4)
{
Throw "IpBytes must be exactly 4 bytes long!"
}
$IpAddress = "$($IpBytes[0]).$($IpBytes[1]).$($IpBytes[2]).$($IpBytes[3])"
}
elseif(![string]::IsNullOrEmpty($HostName))
{
$IpAddresses = Resolve-DnsName -Name $HostName -ErrorAction SilentlyContinue
$entry = $null
if($IpAddresses.Count -gt 1)
{
$entry = $IpAddresses[$IpAddresses.count-1]
}
else
{
$entry = $IpAddresses
}
if([string]::IsNullOrEmpty($entry.IPAddress))
{
if(![string]::IsNullOrEmpty($entry.IP4Address))
{
$IpAddress = $entry.IP4Address
}
else
{
Throw "No ipv address found for $HostName"
}
}
else
{
$IpAddress = $entry.IPAddress
}
}
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://api.ipgeolocationapi.com/geolocate/$IpAddress" -Headers @{"Accept" = "application/json; charset=utf-8"}
if($Short)
{
return @($response.name, $response.subregion, $response.region)
}
else
{
return $response
}
}
}