Skip to content

Instantly share code, notes, and snippets.

@Gravifer
Last active June 20, 2021 13:16
Show Gist options
  • Save Gravifer/a0012ea5f115bf48bc652c1b02845bd8 to your computer and use it in GitHub Desktop.
Save Gravifer/a0012ea5f115bf48bc652c1b02845bd8 to your computer and use it in GitHub Desktop.
PowerShell script to display local weather report

To run this, use

iex ((New-Object System.Net.WebClient).DownloadString("https://gist.githubusercontent.com/Gravifer/a0012ea5f115bf48bc652c1b02845bd8/raw/d6d06a82ed8282e14aed0f258ff39b8e89dcf01e/geo_wttr.ps1"))

Do kindly comment if this does not work for you.

<#
* Author: Gravifer
* Date: 2021, Jul. 14
* Copyright: No copyright. You can use this code for anything with no warranty.
#>
$dependencies = @(
"Write-LocalWeather"
)
foreach ($script in ){
iex ((New-Object System.Net.WebClient).DownloadString("https://gist.githubusercontent.com/Gravifer/a0012ea5f115bf48bc652c1b02845bd8/raw/d6d06a82ed8282e14aed0f258ff39b8e89dcf01e/$script.ps1"))
}
Write-LocalWeather
$dependencies = @(
"Get-GeoLocationCoordinates",
)
foreach ($script in ){
iex ((New-Object System.Net.WebClient).DownloadString("https://gist.githubusercontent.com/Gravifer/a0012ea5f115bf48bc652c1b02845bd8/raw/d6d06a82ed8282e14aed0f258ff39b8e89dcf01e/$script.ps1"))
}
function Get-GeoCodeCoordinatesAddress {
param (
[Parameter(ValueFromPipeline=$true)]
[System.Object[]] $Location = @((Get-GeoLocationCoordinates -l)),
[Double] $TimeoutSec = 0.1
)
foreach ($loc in $location) {
$position = if ($loc -is [String]) {$loc} else { "$($loc.Latitude),$($loc.Longitude)" }
Invoke-RestMethod "https://geocode.xyz/${position}?geoit=json" -TimeoutSec $TimeoutSec
}
}
Set-Alias -Name geoaddr -Value Get-GeoCodeCoordinatesAddress
Function Get-GeoCoordinatesSunriseAndSunset {
[cmdletbinding()]
Param(
[Parameter(Mandatory)]
[double] $Latitude,
[Parameter(Mandatory)]
[double] $Longitude,
[Double] $TimeoutSec = 0.01
)
# Return sunrise/sunset
$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=$Latitude&lng=$Longitude&date=$(Get-Date -Format "yyyy-MM-dd")&formatted=0" -TimeoutSec $TimeoutSec).results
$Daylight
# # Convert to local time datetime objects
# [pscustomobject]@{
# Sunrise = ($Daylight.Sunrise | Get-Date).ToLocalTime()
# Sunset = ($Daylight.Sunset | Get-Date).ToLocalTime()
# }
}
function Get-GeoLocationCoordinates {
param (
[switch]$p=$false,
[switch]$l=$false
)
Add-Type -AssemblyName System.Device # Required to access System.Device.Location namespace
$GeoWatcher = New-Object System.Device.Location.GeoCoordinateWatcher # Create the required object
$GeoWatcher.Start() # Begin resolving current location
while (($GeoWatcher.Status -ne 'Ready') -and ($GeoWatcher.Permission -ne 'Denied')) {
Start-Sleep -Milliseconds 100 # Wait for discovery.
}
if ($GeoWatcher.Permission -eq 'Denied'){
Write-Error 'Access Denied for Location Information'
#// } elseif ($p){
#// $GeoWatcher.Position
} elseif ($l){
$GeoWatcher.Position.Location
} else {
$GeoWatcher.Position.Location | Select-Object Latitude,Longitude # Select the relevent results.
}
}
Set-Alias -Name geo -Value Get-GeoLocationCoordinates
$dependencies = @(
"Get-GeoLocationCoordinates",
"Get-GeoCodeCoordinatesAddress",
"Get-GeoCoordinatesSunriseAndSunset",
)
foreach ($script in ){
iex ((New-Object System.Net.WebClient).DownloadString("https://gist.githubusercontent.com/Gravifer/a0012ea5f115bf48bc652c1b02845bd8/raw/d6d06a82ed8282e14aed0f258ff39b8e89dcf01e/$script.ps1"))
}
<#
.SYNOPSIS
Get weather report from http://wttr.in/ .
.DESCRIPTION
wttr.in β€” the right way to check the weather!
wttr.in is a console-oriented weather forecast service that supports various information representation methods like terminal-oriented ANSI-sequences for console HTTP clients (curl, httpie, or wget), HTML for web browsers, or PNG for graphical viewers .
wttr.in uses wego for visualization and various data sources for weather forecast information .
You can see it running here: http://wttr.in/ .
.PARAMETER h
Get real time help information from http://wttr.in/ .
.PARAMETER Location
Location to get weather report for.
.PARAMETER URL
Usage:
$ curl wttr.in # current location
$ curl wttr.in/muc # weather in the Munich airport
Supported location types:
/paris # city name
/~Eiffel+tower # any location (+ for spaces)
/Москва # Unicode name of any location in any language
/muc # airport code (3 letters)
/@stackoverflow.com # domain name
/94107 # area codes
/-78.46,106.79 # GPS coordinates
Moon phase information:
/moon # Moon phase (add ,+US or ,+France for these cities)
/moon@2016-10-25 # Moon phase for the date (@2016-10-25)
Units:
m # metric (SI) (used by default everywhere except US)
u # USCS (used by default in US)
M # show wind speed in m/s
View options:
0 # only current weather
1 # current weather + today's forecast
2 # current weather + today's + tomorrow's forecast
A # ignore User-Agent and force ANSI output format (terminal)
F # do not show the "Follow" line
n # narrow version (only day and night)
q # quiet version (no "Weather report" text)
Q # superquiet version (no "Weather report", no city name)
T # switch terminal sequences off (no colors)
PNG options:
/paris.png # generate a PNG file
p # add frame around the output
t # transparency 150
transparency=... # transparency from 0 to 255 (255 = not transparent)
background=... # background color in form RRGGBB, e.g. 00aaaa
Options can be combined:
/Paris?0pq
/Paris?0pq&lang=fr
/Paris_0pq.png # in PNG the file mode are specified after _
/Rome_0pq_lang=it.png # long options are separated with underscore
Localization:
$ curl fr.wttr.in/Paris
$ curl wttr.in/paris?lang=fr
$ curl -H "Accept-Language: fr" wttr.in/paris
Supported languages:
am ar af be ca da de el et fr fa hi hu ia id it nb nl oc pl pt-br ro ru tr th uk vi zh-cn zh-tw (supported)
az bg bs cy cs eo es eu fi ga hi hr hy is ja jv ka kk ko ky lt lv mk ml nl fy nn pt pt-br sk sl sr sr-lat sv sw te uz zh zu he (in progress)
Special URLs:
/:help # show this page
/:bash.function # show recommended bash function wttr()
/:translation # show the information about the translators
.EXAMPLE
C:\PS>
<Description of example>
#>
function Get-wttrWeatherReport {
[CmdletBinding(DefaultParameterSetName="Location")]
param (
[Parameter(ValueFromPipeline=$true)]
[System.Object[]] $Location = @((Get-GeoLocationCoordinates -l)),
[string] $Format,
[string] $Locale = (Get-WinSystemLocale).Name,
[string] $Query,
[string] $Version,
[string[]] $URL,
[switch] $h = $false,
[Double] $TimeoutSec = 1
)
if ($h) {
Invoke-RestMethod "http://wttr.in/:help" -TimeoutSec $TimeoutSec
} else {
if (-not $URL) { # ($URL) {$URL = @($URL)} else {
$format = [System.Web.HttpUtility]::UrlEncode($format)
$locale = [System.Web.HttpUtility]::UrlEncode($locale)
if ($Version) {$DNSname = "v$Version"} else {$DNSname = $locale}
if ($query) { $query = "?$query" } else {
$query = if ($format) { "?format=$format" } else {""}
}
[object[]]$URL = foreach ($loc in $location) {
$position = if ($loc -is [String]) {$loc} else { "$(($loc).Latitude),$(($loc).Longitude)" }
[System.Web.HttpUtility]::UrlEncode($position)
}
$URL = ($URL | Join-String -Separator ',')
$URL = (@("wttr.in/{", $URL, "}", $query) | Join-String)
$URL = @(@($DNSname, $URL) | Join-String -Separator '.')
}
foreach ($link in $URL) {
$out = (curl --max-time $TimeoutSec -fGsS -H "Accept-Language: $locale" $link 2>&1)
if ($LastExitCode -ne 0) {
throw (New-Object System.Exception $out)
} else {$out}
} # { Invoke-RestMethod $link}
}
}
Set-Alias -Name wttr -Value Get-wttrWeatherReport
$dependencies = @(
"Get-GeoLocationCoordinates",
"Get-GeoCodeCoordinatesAddress",
"Get-GeoCoordinatesSunriseAndSunset",
"Get-wttrWeatherReport",
)
foreach ($script in ){
iex ((New-Object System.Net.WebClient).DownloadString("https://gist.githubusercontent.com/Gravifer/a0012ea5f115bf48bc652c1b02845bd8/raw/d6d06a82ed8282e14aed0f258ff39b8e89dcf01e/$script.ps1"))
}
function Write-LocalWeather{
[CmdletBinding()]
param (
[System.DateTime] $now = (Get-Date),
[Parameter(ValueFromPipeline=$true)]
[System.Object] $loc = (Get-GeoLocationCoordinates -l),
[Switch] $Fast
)
# $using_wego = $false
$weatherbrief = try {
$addr = try {
$addr = (Get-GeoCodeCoordinatesAddress $loc)
if ((-not $addr.confidence) -or ($addr.confidence -ge 0.5)) {
if (($addr.poi.name) -or ($addr.osmtags.name) -or ($addr.city)){
@($addr.poi.name, $addr.osmtags.name, $addr.city) | Join-String -Separator " "
} elseif ($addr.standard.confidence -ge 0.5) {
@($addr.standard.addresst, $addr.standard.city) | Join-String -Separator " "
} else {
throw (New-Object System.Exception "Cannot find address")
"$([math]::round(($loc).Longitude,3)),$([math]::round(($loc).Latitude,3))"
}
} else {
throw (New-Object System.Exception "Cannot find address")
"$([math]::round(($loc).Longitude,3)),$([math]::round(($loc).Latitude,3))"
}
} catch { Write-Progress " (Address unavailable)" -Status "($loc) $addr" -PercentComplete 100 #-NoNewline -ForegroundColor DarkGray;
"$([math]::round(($loc).Longitude,3)),$([math]::round(($loc).Latitude,3))" }
if ($fast) {Get-wttrWeatherReport -Location $loc -Format "$moonphase%c 🌑️%t (%f πŸ’¦%h 🌬️%w) πŸ’§%p πŸ’¨%P" # -ErrorAction SilentlyContinue
} else {
$test_request = ((Get-wttrWeatherReport -Location $loc -Format "%x %t %f %h %w %p %P %c %m") -split '\s+')
$moonphase = try {
$suntimes = (Get-GeoCoordinatesSunriseAndSunset ($loc).Latitude ($loc).Longitude);
$sunrise = $suntimes.Sunrise; $sunset = $suntimes.Sunset;
$nodaylight = (($now -le $sunrise) -or ($now -ge $sunset))
if ($nodaylight) {$test_request[8]}
} catch { Write-Progress " (Daylight unavailable)" -PercentComplete 100 } # -NoNewline -ForegroundColor DarkGray }
$weather = "$moonphase$(if ((-not $nodaylight) -or ($test_request[0] -ne "o")) {$test_request[7]})"
$precipitation = if (($test_request[0] -match "[/\.x\*\?]") -or
([double]($test_request[5] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+") -gt 0)) {$test_request[5]}
# write-host "percipitation$precipitation $($test_request[0] -match "[/\.x\*\?]") $([double]($test_request[1] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+"))"
}
} catch {
# Write-Progress is a bit of a performance hog. You might reconsider.
Write-Progress " $_" -PercentComplete 100
Write-Host " (Weather unavailable)" -NoNewline -ForegroundColor DarkGray
# $using_wego = $true
}; Write-Host
Write-Host "$($addr): " -NoNewline -ForegroundColor Yellow
if ($false) {wego 4 "$((geo).Latitude),$((geo).Longitude)"
} else {
if ($fast) {Write-Host $weatherbrief -NoNewline} else {
if ($test_request) {Write-Host "$weather$precipitation " -NoNewline
# Switch is nice and compressed, but since it won't have to deal with executing the script block, `if` will be faster.
# Style: You might consider that the only difference between the commands which follow only differ by the start of the message and the colour.
switch ([double]($test_request[1] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+")) {
{($_ -ge 22) -and ($_ -le 25)} {
Write-Host "🌑️$($test_request[1])" -NoNewline -ForegroundColor Green}
{(($_ -ge 20) -and ($_ -lt 22)) -or (($_ -gt 25) -and ($_ -le 28))} {
Write-Host "🌑️$($test_request[1]) " -NoNewline}
{($_ -ge 5) -and ($_ -lt 20)} {
Write-Host "🌑️$($test_request[1]) " -NoNewline -ForegroundColor Cyan}
{($_ -ge -10) -and ($_ -lt 5)} {
Write-Host "🌑️$($test_request[1]) " -NoNewline -ForegroundColor Blue}
{($_ -lt -10)} {
Write-Host "πŸ₯Ά$($test_request[1])" -NoNewline -ForegroundColor DarkBlue}
{($_ -gt 28) -and ($_ -le 34)} {
Write-Host "🌑️$($test_request[1])" -NoNewline -ForegroundColor Yellow}
{($_ -gt 34) -and ($_ -le 40)} {
Write-Host "πŸ₯΅$($test_request[1])" -NoNewline -ForegroundColor Red}
{($_ -gt 40)} {
Write-Host "πŸ”₯$($test_request[1])" -NoNewline -ForegroundColor Magenta}
}
Write-Host "(" -NoNewline
if ($test_request[1] -ne $test_request[2]){
switch ([double]($test_request[2] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+")) {
{($_ -ge 22) -and ($_ -le 25)} {
Write-Host "$($test_request[2]) " -NoNewline -ForegroundColor Green}
{(($_ -ge 20) -and ($_ -lt 22)) -or (($_ -gt 25) -and ($_ -le 28))} {
Write-Host "$($test_request[2]) " -NoNewline}
{($_ -ge 5) -and ($_ -lt 20)} {
Write-Host "$($test_request[2]) " -NoNewline -ForegroundColor Cyan}
{($_ -ge -10) -and ($_ -lt 5)} {
Write-Host "$($test_request[2]) " -NoNewline -ForegroundColor Blue}
{($_ -lt -10)} {
Write-Host "$($test_request[2])" -NoNewline -ForegroundColor DarkBlue}
{($_ -gt 28) -and ($_ -le 32)} {
Write-Host "$($test_request[2]) " -NoNewline -ForegroundColor Yellow}
{($_ -gt 32) -and ($_ -le 40)} {
Write-Host "$($test_request[2])" -NoNewline -ForegroundColor Red}
{($_ -gt 40)} {
Write-Host "$($test_request[2])" -NoNewline -ForegroundColor Magenta}
}}
switch ([double]($test_request[3] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+")) {
{($_ -ge 50) -and ($_ -le 60)} {
Write-Host "πŸ’§$($test_request[3])" -NoNewline -ForegroundColor Green}
{(($_ -ge 40) -and ($_ -lt 50)) -or (($_ -gt 60) -and ($_ -le 70))} {
Write-Host "πŸ’§$($test_request[3])" -NoNewline}
{($_ -gt 70) -and ($_ -le 100)} {
Write-Host "πŸ’¦$($test_request[3])" -NoNewline -ForegroundColor Cyan}
{($_ -gt 100)} {
Write-Host "πŸ’¦$($test_request[3])" -NoNewline -ForegroundColor Blue}
{($_ -ge 20) -and ($_ -lt 40)} {
Write-Host "🏜️$($test_request[3])" -NoNewline -ForegroundColor Yellow}
{($_ -lt 20)} {
Write-Host "πŸͺ$($test_request[3])" -NoNewline -ForegroundColor DarkYellow}
}
switch ([double]($test_request[4] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+")) {
{($_ -gt 0) -and ($_ -le 2)} {
Write-Host " πŸƒ$($test_request[4])" -NoNewline -ForegroundColor DarkGray -Separator ""}
{($_ -gt 2) -and ($_ -le 6)} {
Write-Host " πŸƒ$($test_request[4])" -NoNewline -ForegroundColor Gray -Separator ""}
{($_ -gt 6) -and ($_ -le 19)} {
Write-Host " 🌬️$($test_request[4])" -NoNewline -ForegroundColor Yellow -Separator ""}
{($_ -gt 19) -and ($_ -le 40)} {
Write-Host " 🌬️$($test_request[4])" -NoNewline -ForegroundColor Cyan -Separator ""}
{($_ -gt 40) -and ($_ -le 55)} {
Write-Host " 🌬️$($test_request[4])" -NoNewline -ForegroundColor Blue -Separator ""}
{($_ -gt 55) -and ($_ -le 75)} {
Write-Host " 🌬️$($test_request[4])" -NoNewline -ForegroundColor DarkBlue -Separator ""}
{($_ -gt 75) -and ($_ -le 100)} {
Write-Host " πŸŒͺ️$($test_request[4])" -NoNewline -ForegroundColor Red -Separator ""}
{($_ -gt 100)} {
Write-Host " πŸŒ€$($test_request[4])" -NoNewline -ForegroundColor Magenta -Separator ""}
}; Write-Host "`b) " -NoNewline
switch ([double]($test_request[6] -replace "[^\+\-\d.]" -replace "(?<=\d+\.\d+)\D+")) {
{($_ -gt 1010) -and ($_ -le 1020)} {
Write-Host "πŸ’¨$($test_request[6]) " -NoNewline -ForegroundColor Green}
{(($_ -ge 1005.7) -and ($_ -lt 1010)) -or (($_ -gt 1020) -and ($_ -le 1026))} {
Write-Host "πŸ’¨$($test_request[6]) " -NoNewline}
{($_ -ge 1000) -and ($_ -le 1005.7)} {
Write-Host "πŸ’¨$($test_request[6]) " -NoNewline -ForegroundColor Cyan}
{($_ -lt 1000)} {
Write-Host "πŸ’¨$($test_request[6]) " -NoNewline -ForegroundColor Blue}
{($_ -gt 1026)} {
Write-Host "πŸ’¨$($test_request[6]) " -NoNewline -ForegroundColor Yellow}
}
}
}
}
Write-Host "[$(Get-Date -Format (Get-Culture).DateTimeFormat.FullDateTimePattern)]`n" -ForegroundColor Cyan
}
Set-Alias -Name weather -Value Write-LocalWeather
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment