今天使用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
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
草根站长很不容易啊,坚持下去,加油加油。
有空来麦兜找穿帮官网坐坐哈。诚意交换友链。
http://api.openweathermap.org 此网址已经打不开,看不到效果了,大师能否改一下。谢谢
你把链接中的的api去掉,就可以访问了。要带api,后面应当有参数的,你那样直接访问,肯定404.
$weatherProvider=”http://www.openweathermap.org”这个网站也未试验成功,遗憾看不到效果。
注释掉36-38行代码,您能直接给一个真实的$weatherInfo 数据,主要是想看看桌面提示栏提示信息的效果,感受下powershell的奇妙
其他地方都改对了,但我还是不能看到天气的图片
$balloon.BalloonTipIcon = ‘Info’ 把这句注释掉就看到啦。。原图片太小转成icon不知道怎么放大尺寸