-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-Weather.ps1
79 lines (68 loc) · 2.11 KB
/
Get-Weather.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
67
68
69
70
71
72
73
74
75
76
77
78
79
#region Global enumerations
enum Units
{
kelvin
metric
imperial #default
}
enum DatumTypes
{
Temperature
Pressure
WindSpeed
CloudCover
}
#endregion
function Get-Weather
{
[cmdletbinding(DefaultParameterSetName = "coord")]
param
(
[Parameter(ParameterSetName = "coord")]
[array]$Coordinates = @(),
[Parameter(ParameterSetName = "city")]
[string]$City="Philadelphia",
[Parameter(ParameterSetName = "city")]
[string]$CountryCode="US",
[Parameter(ParameterSetName = "coord")]
[Parameter(ParameterSetName = "city")]
[Units[]]
$Unit=[Units]::imperial,
[Parameter(ParameterSetName = "coord")]
[Parameter(ParameterSetName = "city")]
[switch]$PassThru
)
#Set up query parameters
$endpoint = $Global:WEATHER_SETTINGS.settings.api.weather.endpoint
$key = $Global:WEATHER_SETTINGS.settings.api.weather.key
$unitVal = if ($Unit -ne [Units]::kelvin) {"&units={0}" -f ($Unit -as [string])} else {""}
#Build the weather API query
if ($PSCmdlet.ParameterSetName -eq "coord")
{
if ($Coordinates.Count -ne 2)
{
$Coordinates = Get-MyLocation
$Coordinates = @($Coordinates.lat, $Coordinates.lon)
}
$query = "?lat={0}&lon={1}{2}" -f ($Coordinates + ,$unitVal)
}
elseif ($PSCmdlet.ParameterSetName -eq "city")
{
$query = "?q={0},{1}{2}" -f $City,$CountryCode,$unitVal
}
$request = $endpoint + $query + ("&APPID={0}" -f $key)
#Make a request to the weather API to get the weather data
try
{
$weatherData = Invoke-RestMethod $request
}
catch
{
Write-Host "Unable to get weather data from endpoint: `n`t$endpoint" -ForegroundColor $Host.PrivateData.ErrorForegroundColor
Write-Host $_ -ForegroundColor $Host.PrivateData.ErrorForegroundColor
return $null
}
#Print out the weather report and optionally return the raw weather data
Write-Weather -WeatherData $weatherData -Unit $Unit
if ($PassThru) {return $weatherData}
}