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

[玩转系统] 宝贝外面很冷

作者:精品下载站 日期:2024-12-14 07:44:52 浏览:14 分类:玩电脑

宝贝外面很冷


我不知道你的情况如何,但这里完全是北极。所以我想完善我的 PowerShell 函数来获取天气数据。

#requires -version 3.0

Function Get-MyWeather {
<#
.Synopsis
Get the weather for a US zip code
.Description
This command will query the Yahoo weather service and return weather conditions for a US zip code.
.Example
PS C:\> get-myweather 98133

Location    : Seattle, WA
Date        : 2/16/2015 4:53:00 AM
Temperature : 45
Low         : 38
High        : 60
Conditions  : Mostly Cloudy

.Notes
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
Invoke-RestMethod
#>

Param(
[Parameter(Position=0,HelpMessage="Enter a United States zip code")]
[ValidateNotNullorEmpty()]
[string]$Zip='00000'
)

#construct the URI
$uri = "http://xml.weather.yahoo.com/forecastrss?p=$Zip"

Try {
    #gets XML data
    $data = Invoke-RestMethod -Uri $uri -ErrorAction Stop

    write-verbose ($data | out-string)
    if ($data.title -ne 'city not found') {

        #get title string and parse out location and time using
        #named regular expression captures
       
        $rx = "(?<location>\S+,\s\S+) at (?<time>\d{1,2}:\d{2}\s(a|p)m)"
        $data.title -match $rx | out-Null      
        Write-Verbose ($matches | out-string)
        $location = $matches.location
        $dt = $matches.time -as [datetime]

        #write a custom object to the pipeline
        [pscustomobject][ordered]@{
         Location    = $location
         Date        = $dt
         Temperature = $data.condition.temp -as [int]
         Low         = $data.forecast[0].low -as [int]
         High        = $data.forecast[0].high -as [int]
         Conditions  = $data.condition.text
        } #close hash table 
    }
    else {
        Write-Warning "No city found for zip code $zip"
    }
} #Try
Catch {
    #throw the exception
    Throw $_
}

} #end function

此功能使用美国地点的雅虎天气 RSS 源。该函数使用 Invoke-RestMethod 来获取给定邮政编码的条目。我将我的邮政编码设置为默认值,并建议您也这样做。您需要修改上面代码中的默认值。 Invoke-RestMethod 为我提供了一个 XML 文档,因此提取我想要的值并构造自定义对象并不是太困难。我什至使用一些名为 captures 的正则表达式来分解位置和时间。所以希望这里有一些很好的学习例子。

反正这里挺冷的,比我起床的时候已经暖和了五度了。

[玩转系统] 宝贝外面很冷

希望你保持温暖。

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

取消回复欢迎 发表评论:

关灯