PowerShell 在桌面提示栏显示天气信息 7


今天使用PowerShell 获取天气预报的信息,在桌面的右下角提示栏显示。

需求

Powerhell在Windows桌面的右下角显示天气提示信息,内容包括当前的城市,天气描述,和气温信息。

知识点

  • PowerShell使用WebRequest来请求远程web内容
  • PowerShell将Json字符串转换成对象
  • PowerShell将png图像转换成ico图像
  • PowerShell在桌面提示栏显示气球提示

脚本实现

# Convert image bytes to icon format
function ConvertTo-Icon( [byte[]]$pngBuffer )
{
    $pngStream=$null
    [void]($pngStream =New-Object 'io.memorystream' $pngBuffer,$true)
    $img=[System.Drawing.Image]::FromStream($pngStream)
    $icon=[System.Drawing.Icon]::FromHandle($img.GetHicon())
    return $icon
}

# Show ballon tip notification 
function Show-NotifyIcon([System.Drawing.Icon]$icon,[string]$title,[string]$message)
{
    $balloon = New-Object System.Windows.Forms.NotifyIcon
    if($icon) 
    { 
        $balloon.Icon = $icon 
    }
    else 
    {
        $psProcPath =  Get-Process -id $pid | Select-Object -ExpandProperty Path
        $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon( $psProcPath )
    }
    $balloon.BalloonTipIcon = 'Info'
    $balloon.BalloonTipText = $message
    $balloon.BalloonTipTitle = $title
    $balloon.Visible = $true
    $balloon.ShowBalloonTip(10000)
    sleep -Seconds 3
    $balloon.Dispose()
}

# show weather notification
function Show-WeatherNotification([string]$cityName="Shanghai")
{
    $weatherRequest =Invoke-WebRequest ( "$weatherProvider/data/2.5/weather?q={0}" -f $cityName )
    $weatherInfo = $weatherRequest | ConvertFrom-Json

    $message=‘’

    if($weatherInfo.cod -eq '200')
    {
        $temp_const = 273.15

        $city = $weatherInfo.name
        $des = $weatherInfo.weather.description
        $max_temp = [math]::Round( $weatherInfo.main.temp_max - $temp_const,1)
        $min_temp = [math]::Round( $weatherInfo.main.temp_min - $temp_const,1)
        $message="{0}: {1}`nTemperature({2}-{3})" -f $city,$des,$max_temp,$min_temp
    }

    # Weather image flag
    $iconName = $weatherInfo.weather.icon
    [byte[]]$pngBuffer = (Invoke-WebRequest -Uri "$weatherProvider/img/w/$iconName.png" ).Content
    [System.Drawing.Icon]$icon = ConvertTo-Icon -pngBuffer $pngBuffer
    Show-NotifyIcon -icon $icon -title ‘Weather info from PStips.net’ -message $message
}
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'System.Windows.Forms'
$weatherProvider="http://api.openweathermap.org"

#sample
Show-WeatherNotification -cityName Shanghai

 

本文链接: https://www.pstips.net/powershell-show-weather-info.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

7 条评论 “PowerShell 在桌面提示栏显示天气信息