当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 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

[玩转系统] PowerShell 天气服务

该对象还有方法:

[玩转系统] PowerShell 天气服务

那么如何使用 GetWeather 方法呢?

[玩转系统] PowerShell 天气服务

看起来很直接。咱们试试吧。想知道温暖的地方是什么样子吗?

[玩转系统] PowerShell 天气服务

有趣的。我可以阅读它,但这看起来确实像 XML。如果是这样,我应该能够以 XML 文档的形式检索天气。

[xml]$current = $proxy.GetWeather("Miami","United States")

现在我可以探索它了。

[玩转系统] PowerShell 天气服务

哇。这看起来很简单。我所需要的只是 CurrentWeather 属性,并且我有一个易于阅读的结果。我可能可以将其作为一句台词来运行。

([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Fairbanks","United States"))).CurrentWeather

不一定容易阅读,但它确实有效。

[玩转系统] PowerShell 天气服务

那另一个城市呢?也许是北卡罗来纳州夏洛特市即将召开的 PowerShell 峰会的举办地。

([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Charlotte","United States"))).CurrentWeather

[玩转系统] PowerShell 天气服务

好吧,这很有效,但这不是我想要的城市。回到网络服务方法,我记得看到过一些按国家/地区获取城市的东西。让我们试试吧。

$proxy.GetCitiesByCountry("Nepal")

[玩转系统] PowerShell 天气服务

更多 XML。这就是找到。我可以使用 Select-XML 解析出 City 节点。

$proxy.GetCitiesByCountry("Nepal") | select-xml "//City"

[玩转系统] PowerShell 天气服务

现在,展开每个节点。

$proxy.GetCitiesByCountry("Nepal") | select-xml "//City" | select -expand node

[玩转系统] PowerShell 天气服务

现在让我们尝试在美国查找名称中包含夏洛特的城市。

$proxy.GetCitiesByCountry("United States") | select-xml "//City" | select -expand node | Where {$_.'#text' -match "Charlotte"}

[玩转系统] PowerShell 天气服务

在我看来,气象服务数据主要来自有机场的地点。因此,如果您住在没有机场的城镇,最好的办法就是找到您附近有机场的地点。但现在我知道北卡罗来纳州夏洛特需要什么,我可以修改我的命令。

([xml]((New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL).GetWeather("Charlotte / Douglas","United States"))).CurrentWeather

[玩转系统] PowerShell 天气服务

好多了。但我不想为所有这些做那么多的输入,所以我组合了一些函数来简化整个过程。首先,是获取位置的函数。

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 服务代理和按国家/地区检索城市的所有工作。您可以将默认值更改为您所在的国家/地区。我还添加了一个与城市名称匹配的参数。

[玩转系统] PowerShell 天气服务

然后我编写了一个函数来更容易地获取天气信息。

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 时,发现了一些小问题。第一,风节点被重复,因此我决定将两者合并为一个属性。我还注意到一些节点值有额外的空格。因此,我修剪了这些值,因为我构建了一个有序的哈希表,然后将其转换为自定义对象。最终结果是一个易于使用的工具。

[玩转系统] PowerShell 天气服务

您甚至可以在命令之间进行管道传输。

get-weatherlocation -city chicago | get-weatherbyproxy | Out-GridView -title "Chicago"

[玩转系统] PowerShell 天气服务

对象属性都是字符串,这意味着排序或过滤很麻烦,但这里有一些很好的数据,所以我想这是一个权衡。

现在,假设您不能简单地看窗外,您可以通过多种方式查看天气。希望您在此过程中学到了一些有关 PowerShell 的新知识。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯