[玩转系统] 获取地球上哪个地方的天气
作者:精品下载站 日期:2024-12-14 07:44:54 浏览:12 分类:玩电脑
获取地球上哪个地方的天气
昨天我发布了一篇关于使用 Invoke-WebRequest 获取天气状况的热门文章。该功能使用雅虎网站,但实际上只适用于美国城市。因此,我还清理并修改了另一组高级 PowerShell 函数(需要 PowerShell 3),这些函数可以检索地球上可能任何位置的天气信息。您需要的第一条信息是您的 WOEID,即“地球上的位置 ID”。这是一个可以做到这一点的函数。
Function Get-Woeid {
<#
.Synopsis
Retrieve WOEID information
.Description
Search Yahoo's Geo Places for a WOEID (Where On Earth ID). You can search based on a postal code, or place name. Optionally, you can save the XML results to the pipeline.
.Parameter Search
A search parameter such as a postal or zip code. You can also use a place name.
.Parameter AsXML
Write the XML document to the pipeline.
.Example
PS C:\> get-woeid 89101
Country : US
Region : Nevada
Postal : 89101
Locale : Las Vegas
WOEID : 12795439
.Example
PS C:\> get-woeid -search "H1A0A1"
Region : Quebec
Postal : H1A 0A1
WOEID : 55963829
Locale : Montreal
Country : CA
.Example
PS C:\> get-woeid "Helsinki, Finland"
Country : FI
Region : Uudenmaan maakunta
Postal :
Locale : Helsinki
WOEID : 565346
.Example
PS C:\> get-woeid "Helsinki, Finland" | get-weather -unit C
Date : Mon, 16 Feb 2015 4:49 pm EET
Location : Helsinki, Finland
Temperature : -2 C
Condition : Fair
ForecastCondition : Clear
ForecastLow : -6 C
ForecastHigh : -2 C
.Example
PS C:\> [xml]$doc = get-woeid "omaha, ne" -AsXML
PS C:\> $doc.Save("c:\work\omahaid.xml")
The first command gets the raw XML document and the second command writes it to disk. Or you can explore the document interactively.
PS C:\> $doc.query.results.place.timezone
type woeid #text
---- ----- -----
Time Zone 56043661 America/Chicago
.Inputs
strings
.Outputs
custom object
.Link
Invoke-RestMethod
.Notes
NAME: Get-Woeid
VERSION: 3.0
AUTHOR: Jeffery Hicks
LASTEDIT: February 16, 2015
Learn more about PowerShell:
Essential PowerShell Learning Resources
#>
Param(
[parameter(Position=0,Mandatory,ValueFromPipeline,
HelpMessage="Enter a place name or postal (zip) code.")]
[string[]]$Search,
[switch]$AsXML
)
Begin {
Write-Verbose "Starting $($myinvocation.mycommand)"
}
Process {
foreach ($item in $search) {
Write-Verbose "Querying for $search"
$uri = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D'$ITEM'%20limit%201"
Write-Verbose $uri
[xml]$xml= Invoke-RestMethod -Uri $uri
if ($AsXML) {
Write-Verbose "Writing XML document"
$xml
Write-Verbose "Ending function"
#bail out since we're done
Return
}
if ($xml.query.results.place.woeid) {
Write-Verbose "Parsing XML into an ordered hashtable"
$hash = [ordered]@{
WOEID = $xml.query.results.place.woeid
Locale = $xml.query.results.place.locality1.'#text'
Region = $xml.query.results.place.admin1.'#text'
Postal = $xml.query.results.place.postal.'#text'
Country = $xml.query.results.place.country.code
}
Write-Verbose "Writing custom object"
New-Object -TypeName PSObject -Property $hash
} #if $xml
else {
Write-Warning "Failed to find anything for $item"
}
} #foreach
} #process
End {
Write-Verbose "Ending $($myinvocation.mycommand)"
}
} #end function
要使用该功能,您需要指定某种搜索条件,例如邮政编码或城市名称。
我将 WOEID 作为变量保存在 PowerShell 配置文件中。该函数也使用Invoke-RestMethod。我添加了一个参数来将 XML 文档写入管道,以防您想要修改函数并需要一些帮助来发现数据。第二个函数 Get-Weather 使用 WOIED 获取当前天气状况。它也使用 Invoke-RestMethod 来检索数据。然后使用 Select-XML 解析生成的 XML 文档以构建输出对象。
Function Get-Weather {
<#
.Synopsis
Retrieve weather information from Yahoo.com.
.Description
Using the Yahoo weather APIs, this function will retrieve weather information for the specified WOEID or "Where on Earth ID". If you don't know your WOED, open a web browser and go to http://weather.yahoo.com/. Enter in your zip or postal code. Your WOEID will be the number at the end of the url.
Or you can use the Get-Woeid function.
A custom object is written to the pipeline and you can control how much information is displayed by specifying Basic, Extended or All for the Detail parameter.
Basic properties:
Date,Location,Temperature,Condition,ForecastCondition,ForecastLow, and ForecastHigh. This is the default.
Extended properties:
Basic properties plus WindChill,WindSpeed,Humidity,Barometer,Visibility,and Tomorrow.
All properties:
Extended properties plus Sunrise,Sunset,City,Region,Zip,Latitude,Longitude,URL
.Parameter Woeid
Your WOEID, or "Where on Earth ID".
.Parameter Unit
Show temperature in Farenheit or Celsius
.Parameter Online
Open the web page in your default browser.
.Parameter AsXML
Write an XML document to the pipeline.
.Example
PS C:> get-weather 12795711
Date : Mon, 16 Feb 2015 3:51 am PST
Location : Beverly Hills, CA
Temperature : 56 F
Condition : Fair
ForecastCondition : Sunny
ForecastLow : 55 F
ForecastHigh : 72 F
.Example
PS C:\> get-weather 12795446 extended
Date : Mon, 16 Feb 2015 6:56 am PST
Location : Las Vegas, NV
Temperature : 52 F
Condition : Mostly Cloudy
ForecastCondition : Sunny
ForecastLow : 49 F
ForecastHigh : 77 F
WindChill : 52 F
WindSpeed : 9 mph
Humidity : 35%
Barometer : 29.95 in and steady
Visibility : 10 mi
Tomorrow : Tue 17 Feb 2015 Sunny Low 49F: High: 70F
.Example
PS C:\> 12795711,12795446,12762736 | Get-Weather -detail all | Format-Table City,Temperature,Condition,Sunrise,Sunset
City Temperature Condition Sunrise Sunset
---- ----------- --------- ------- ------
Beverly Hills 56 F Fair 6:37 am 5:38 pm
Las Vegas 52 F Mostly Cloudy 6:26 am 5:21 pm
Syracuse -3 F Partly Cloudy 7:01 am 5:34 pm
.Example
PS C:\> get-woeid "Bangor,ME" | get-weather
Date : Mon, 16 Feb 2015 9:51 am EST
Location : Bangor, ME
Temperature : 5 F
Condition : Partly Cloudy
ForecastCondition : Partly Cloudy/Wind
ForecastLow : -6 F
ForecastHigh : 12 F
.Example
PS C:\> get-woeid "Juneau, AK","Miami,FL" | get-weather | Select Date,Location,Temperature
Date Location Temperature
---- -------- -----------
Mon, 16 Feb 2015 8:54 am AKST Juneau, AK 35 F
Mon, 16 Feb 2015 12:53 pm EST Miami, FL 75 F
.Inputs
Strings
.Outputs
Custom object
.Link
Invoke-RestMethod
.Link
Get-Woeid
Select-XML
.Notes
NAME: Get-Weather
VERSION: 3.0
AUTHOR: Jeffery Hicks
LASTEDIT: February 16, 2015
Learn more about PowerShell:
Essential PowerShell Learning Resources
****************************************************************
* DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
* THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF *
* YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
* DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. *
****************************************************************
#>
[cmdletbinding(DefaultParameterSetName="detail")]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter a WOEID value",
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[ValidateNotNullorEmpty()]
[string[]]$woeid,
[Parameter(Position=1,ParameterSetName="detail")]
[ValidateSet("Basic","Extended","All")]
[String]$Detail="Basic",
[ValidateSet("f","c")]
[String]$Unit="f",
[Parameter(ParameterSetName="online")]
[Switch]$Online,
[Parameter(ParameterSetName="xml")]
[Switch]$AsXML
)
Begin {
Write-Verbose "Starting $($myinvocation.mycommand)"
#define property sets
$BasicProp=@("Date","Location","Temperature","Condition","ForecastCondition",
"ForecastLow","ForecastHigh")
$ExtendedProp=$BasicProp
$ExtendedProp+=@("WindChill","WindSpeed","Humidity","Barometer",
"Visibility","Tomorrow")
$AllProp=$ExtendedProp
$AllProp+=@("Sunrise","Sunset","City","Region","Latitude",
"Longitude","ID","URL")
#unit must be lower case
$Unit=$Unit.ToLower()
Write-Verbose "Using unit $($unit.toLower())"
#define base url string
[string]$uribase = "http://weather.yahooapis.com/forecastrss"
Write-Verbose "Base = $uribase"
} #begin
Process {
Write-Verbose "Processing"
foreach ($id in $woeid) {
Write-Verbose "Getting weather info for woeid: $id"
#define a uri for the given WOEID
[string]$uri = "{0}?w={1}&u={2}" -f $uribase,$id,$unit
if ($online) {
Write-Verbose "Opening $uri in web browser"
Start-Process -FilePath $uri
#bail out since there's nothing else to do.
Return
}
Write-Verbose "Downloading $uri"
[xml]$xml= Invoke-WebRequest -uri $uri
if ($AsXML) {
Write-Verbose "Writing XML document"
$xml
Write-Verbose "Ending function"
#bail out since we're done
Return
}
if ($xml.rss.channel.item.Title -eq "City not found") {
Write-Warning "Could not find a location for $id"}
else {
Write-Verbose "Processing xml"
#initialize a new hash table
$properties=@{}
<#
get the yweather nodes
yweather information comes from a different namespace so we'll
use Select-XML to extract the data. Parsing out all data regardless
of requested detail since it doesn't take much effort. Later,
only the requested detail will be written to the pipeline.
#>
#define the namespace hash
$namespace=@{yweather=$xml.rss.yweather}
$units=(Select-Xml -xml $xml -XPath "//yweather:units" -Namespace $namespace ).node
$properties.Add("Condition",$xml.rss.channel.item.condition.text)
$properties.Add("Temperature","$($xml.rss.channel.item.condition.temp) $($units.temperature)")
#convert Date to a [datetime] object
$dt = $xml.rss.channel.item.condition.date.Substring(0,$xml.rss.channel.item.condition.Date.LastIndexOf("m")+1) -as [datetime]
$properties.Add("Date",$dt)
#get forecast
$properties.add("ForecastDate",$xml.rss.channel.item.forecast[0].date)
$properties.add("ForecastCondition",$xml.rss.channel.item.forecast[0].text )
$properties.Add("ForecastLow","$($xml.rss.channel.item.forecast[0].low) $($units.temperature)" )
$properties.Add("ForecastHigh","$($xml.rss.channel.item.forecast[0].high) $($units.temperature)" )
#build tomorrow's foreacst
$t=$xml.rss.channel.item.forecast[1]
$tomorrow="{0} {1} {2} Low {3}{4}: High: {5}{6}" -f $t.day,$t.Date,$t.Text,$t.low, $($units.temperature),$t.high, $($units.temperature)
$properties.add("Tomorrow",$tomorrow)
#get optional information
$properties.Add("Latitude",$xml.rss.channel.item.lat)
$properties.Add("Longitude",$xml.rss.channel.item.long)
$city=$xml.rss.channel.location.city
$properties.Add("City",$city)
$region=$xml.rss.channel.location.region
$country=$xml.rss.channel.location.country
if (-not ($region)) {
#if no region found then use country
Write-Verbose "No region found. Using Country"
$region=$country
}
$properties.Add("Region",$region)
$location="{0}, {1}" -f $city,$region
$properties.Add("Location",$location)
$properties.Add("ID",$id)
#get additional yweather information
$wind=(Select-Xml -xml $xml -XPath "//yweather:wind" -Namespace $namespace ).node
$astronomy=(Select-Xml -xml $xml -XPath "//yweather:astronomy" -Namespace $namespace ).node
$atmosphere=(Select-Xml -xml $xml -XPath "//yweather:atmosphere" -Namespace $namespace ).node
$properties.Add("WindChill","$($wind.chill) $($units.temperature)")
$properties.Add("WindSpeed","$($wind.speed) $($units.speed)")
$properties.Add("Humidity","$($atmosphere.humidity)%")
$properties.Add("Visibility","$($atmosphere.visibility) $($units.distance)")
#decode rising
switch ($atmosphere.rising) {
0 {$state="steady"}
1 {$state="rising"}
2 {$state="falling"}
}
$properties.Add("Barometer","$($atmosphere.pressure) $($units.pressure) and $state")
$properties.Add("Sunrise",$astronomy.sunrise)
$properties.Add("Sunset",$astronomy.sunset)
$properties.Add("url",$uri)
#create new object to hold values
$obj= New-Object -TypeName PSObject -Property $properties
#write object and properties. Default is Basic
Switch ($detail) {
"All" {
Write-Verbose "Using All properties"
$obj | Select-Object -Property $AllProp
} #all
"Extended" {
Write-Verbose "Using Extended properties"
$obj | Select-Object -Property $ExtendedProp
} #extended
Default {
Write-Verbose "Using Basic properties"
$obj | Select-Object -Property $BasicProp
} #default
} #Switch
} #processing XML
} #foreach $id
} #process
End {
Write-Verbose "Ending $($myinvocation.mycommand)"
} #end
} #end function
您还可以更改温度单位。
我将它们编写为两个单独的函数,我想我可以将 Get-Woeid 嵌套在 Get-Weather 中,尽管更好的选择可能是构建一个模块。我把它留给你。这些函数旨在利用管道绑定,以便您可以通过管道将 Get-Woeid 传递给 Get-Weather。
您甚至可以获得多个地点的天气。
该天气源包含大量信息,因此我创建了一个参数来控制要显示的详细信息量。您在上面看到的是基本信息。但还有‘延长’。
或者,您可以通过“全部”详细设置来查看所有内容。
注意到最后的那个网址了吗?最重要的是,您可以使用“在线”参数在浏览器中打开天气预报。
get-woeid 13244 | get-weather -Online
你有它。无论您身在何处,都可以查看天气。或者看看窗外。
享受。
- 上一篇:[玩转系统] 宝贝外面很冷
- 下一篇:[玩转系统] PowerShell 天气服务
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag