[玩转系统] PowerShell 天气服务
作者:精品下载站 日期:2024-12-14 07:44:58 浏览:14 分类:玩电脑
PowerShell 天气服务
本周我很开心地分享了一些使用 PowerShell 获取天气信息和预报的工具。为了完成这个故事,今天我还有一项技巧。使用 PowerShell,您可以查询 Web 服务以获取天气信息。简单来说,网络服务就像一个可以通过网络连接“运行”的应用程序,有时甚至可以在浏览器中“运行”。 Web 服务具有您可以调用来执行某些操作的“方法”。过去,如果您想在 PowerShell 中与 Web 服务交互,您很可能需要深入了解 .NET Framework。然后PowerShell 3.0给我们带来了一个新的cmdlet,New-WebServiceProxy。使用此 cmdlet,您可以创建一个对象,该对象本质上成为 Web 服务的包装器。 Web 服务方法成为对象的方法。我来给你展示。
首先,我将创建我的代理对象。
$proxy = New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL
该对象还有方法:
那么如何使用 GetWeather 方法呢?
看起来很直接。咱们试试吧。想知道温暖的地方是什么样子吗?
有趣的。我可以阅读它,但这看起来确实像 XML。如果是这样,我应该能够以 XML 文档的形式检索天气。
[xml]$current = $proxy.GetWeather("Miami","United States")
现在我可以探索它了。
哇。这看起来很简单。我所需要的只是 CurrentWeather 属性,并且我有一个易于阅读的结果。我可能可以将其作为一句台词来运行。
([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Fairbanks","United States"))).CurrentWeather
不一定容易阅读,但它确实有效。
那另一个城市呢?也许是北卡罗来纳州夏洛特市即将召开的 PowerShell 峰会的举办地。
([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Charlotte","United States"))).CurrentWeather
好吧,这很有效,但这不是我想要的城市。回到网络服务方法,我记得看到过一些按国家/地区获取城市的东西。让我们试试吧。
$proxy.GetCitiesByCountry("Nepal")
更多 XML。这就是找到。我可以使用 Select-XML 解析出 City 节点。
$proxy.GetCitiesByCountry("Nepal") | select-xml "//City"
现在,展开每个节点。
$proxy.GetCitiesByCountry("Nepal") | select-xml "//City" | select -expand node
现在让我们尝试在美国查找名称中包含夏洛特的城市。
$proxy.GetCitiesByCountry("United States") | select-xml "//City" | select -expand node | Where {$_.'#text' -match "Charlotte"}
在我看来,气象服务数据主要来自有机场的地点。因此,如果您住在没有机场的城镇,最好的办法就是找到您附近有机场的地点。但现在我知道北卡罗来纳州夏洛特需要什么,我可以修改我的命令。
([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Charlotte / Douglas","United States"))).CurrentWeather
好多了。但我不想为所有这些做那么多的输入,所以我组合了一些函数来简化整个过程。首先,是获取位置的函数。
Function Get-WeatherLocation {
<#
.SYNOPSIS
Get weather locations via web service proxy
.DESCRIPTION
This command will get all cities for a given country using a web service proxy designed to retrieve weather conditions.
.PARAMETER Country
The name of the country in English.
.PARAMETER City
Some portion of the name of a city or area. The command will match on the pattern so regular expressions are permitted.
.EXAMPLE
PS C:\> Get-WeatherLocation Albania
City Country
---- -------
Tirana Albania
.EXAMPLE
PS C:\> Get-Weatherlocation -city "chicago"
City Country
---- -------
Chicago / Meigs United States
Chicago / West Chicago, Dupage Airport United States
Chicago, Chicago Midway Airport United States
Chicago, Chicago-O'Hare International Air... United States
Chicago / Wheeling, Pal-Waukee Airport United States
Chicago / Waukegan United States
Find all US locations that have "Chicago" in the name.
.NOTES
NAME : Get-WeatherLocation
VERSION : 1.0
LAST UPDATED: 2/19/2015
AUTHOR : Jeff Hicks
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. *
****************************************************************
.LINK
New-WebServiceProxy
.INPUTS
None
.OUTPUTS
Custom object
#>
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline)]
[ValidateNotNullorEmpty()]
[string]$Country="United States",
[string]$City
)
Begin {
Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"
Try {
#hashtable of parameters to splat to New-WebServiceProxy
$paramHash = @{
uri = 'http://www.webservicex.com/globalweather.asmx?WSDL'
ErrorAction = 'Stop'
}
Write-Verbose "Creating web proxy to $($paramHash.uri)"
$webproxy = New-WebServiceProxy @paramHash
}
Catch {
Throw $_
}
} #begin
Process {
If ($webproxy) {
[xml]$cities = $webproxy.GetCitiesbyCountry($Country)
#only continue if there is data to process
if ($cities.NewDataset) {
#this will write a new object to the pipeline with 2 properties
$data = $cities.NewDataSet.table | select City,Country
}
Else {
Write-Warning "Failed to retrieve cities for $country"
}
if ($City) {
$data | where {$_.city -match $City}
}
else {
#write all data to the pipeline
$data
}
} #if webproxy
} #process
End {
Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #end
} #end function
Set-Alias -Name gwl -Value Get-WeatherLocation
该函数完成创建 Web 服务代理和按国家/地区检索城市的所有工作。您可以将默认值更改为您所在的国家/地区。我还添加了一个与城市名称匹配的参数。
然后我编写了一个函数来更容易地获取天气信息。
Function Get-WeatherByProxy {
<#
.SYNOPSIS
Get weather conditions via a web service proxy
.DESCRIPTION
This command uses the New-WebServiceProxy cmdlet to retrieve weather information from a web service.
.PARAMETER City
The name of the city or location. This works best if the city has an airport. You can also use part of the airport name.
.PARAMETER Country
The name of the country in English.
.EXAMPLE
PS C:\> Get-Weatherbyproxy Seattle
Location : SEATTLE-TACOMA INTERNATIONAL AIRPORT , WA, United States (KSEA)
47-27N 122-19W 136M
Time : Feb 18, 2015 - 08:53 AM EST / 2015.02.18 1353 UTC
Wind : from the SE (130 degrees) at 8 MPH (7 KT):0
Visibility : 10 mile(s):0
SkyConditions : partly cloudy
Temperature : 43.0 F (6.1 C)
DewPoint : 39.0 F (3.9 C)
RelativeHumidity : 85%
Pressure : 30.18 in. Hg (1022 hPa)
Status : Success
Get the weather in Seattle.
.EXAMPLE
PS C:\> Get-WeatherbyProxy "O'Hare" | Select Time,Sky*,Temperature
Time SkyConditions Temperature
---- ------------- -----------
Feb 18, 2015 - 09:51 AM ES... partly cloudy 5.0 F (-15.0 C)
Get the weather in Chicago using O'Hare airport as the source.
.EXAMPLE
PS C:\> Get-Weatherbyproxy Oslo Norway
Location : Oslo / Gardermoen, Norway (ENGM) 60-12N 011-05E 204M
Time : Feb 18, 2015 - 09:50 AM EST / 2015.02.18 1450 UTC
Wind : from the S (190 degrees) at 12 MPH (10 KT):0
Visibility : greater than 7 mile(s):0
SkyConditions : mostly cloudy
Temperature : 39 F (4 C)
DewPoint : 33 F (1 C)
RelativeHumidity : 80%
Pressure : 29.94 in. Hg (1014 hPa)
Status : Success
.Example
PS C:\> Get-WeatherLocation "united states" -city "Charlotte" | get-weatherbyproxy | out-gridview -title Weather
This command uses a related function called Get-WeatherLocation to find all US locations that have Charlotte in the name and retrieves the weather for each location. Results are displayed using Out-Gridview.
.NOTES
NAME : Get-WeatherByProxy
VERSION : 1.0
LAST UPDATED: 2/18/2015
AUTHOR : Jeff Hicks
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. *
****************************************************************
.LINK
New-WebServiceProxy
.INPUTS
Strings
.OUTPUTS
Custom object
#>
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory,
HelpMessage="Enter the name of a city. Preferably one with an airport",
ValueFromPipeline,ValueFromPipelineByPropertyname)]
[ValidateNotNullorEmpty()]
[string[]]$City,
[Parameter(Position=1,ValueFromPipelineByPropertyname)]
[ValidateNotNullorEmpty()]
[string]$Country = "United States"
)
Begin {
Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"
Try {
#hashtable of parameters to splat to New-WebServiceProxy
$paramHash = @{
uri = 'http://www.webservicex.com/globalweather.asmx?WSDL'
ErrorAction = 'Stop'
}
Write-Verbose "Creating web proxy to $($paramHash.uri)"
$webproxy = New-WebServiceProxy @paramHash
}
Catch {
Throw $_
}
} #begin
Process {
#only process if there is a proxy object
if ($webproxy) {
foreach ($location in $city) {
Write-Verbose "Getting weather for $location, $country"
Try {
#result is XML so let's make it an object
[xml]$doc = $webproxy.GetWeather($location,$country)
Write-Debug ($doc.CurrentWeather | out-string)
#get the child nodes which will be the properites
#but omit Status since we don't need it.
$properties = $doc.CurrentWeather.ChildNodes.name |
Where {$_ -ne 'Status'} | Select -Unique
#create a custom object and add each property value trimmed
#of extra spaces
$propHash = [ordered]@{}
#there are duplicate node names so we'll join them
#into a single property
foreach ($property in $properties) {
Write-Debug $property
$value = ($doc.currentWeather | select-xml "//$property" | select -expand Node).'#text'.trim() -join " "
$propHash.Add($property,$value)
}
Write-Debug ($propHash | out-string)
#Write the result
[pscustomobject]$propHash
} #try xml
Catch {
Write-Warning "Failed to find weather information for $location, $country"
Write-Warning $_.exception.message
} #catch
} #foreach location
} #if $weather
} # process
End {
Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #end
} #end function
Set-Alias -Name gwp -Value Get-WeatherByProxy
在查看 XML 时,发现了一些小问题。第一,风节点被重复,因此我决定将两者合并为一个属性。我还注意到一些节点值有额外的空格。因此,我修剪了这些值,因为我构建了一个有序的哈希表,然后将其转换为自定义对象。最终结果是一个易于使用的工具。
您甚至可以在命令之间进行管道传输。
get-weatherlocation -city chicago | get-weatherbyproxy | Out-GridView -title "Chicago"
对象属性都是字符串,这意味着排序或过滤很麻烦,但这里有一些很好的数据,所以我想这是一个权衡。
现在,假设您不能简单地看窗外,您可以通过多种方式查看天气。希望您在此过程中学到了一些有关 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