Powershell可以很輕松的獲取網頁的信息并讀取到對應的內容。如果對象的格式是XML或者Json,那就更容易處理了,一般經常使用invoke-restmethod和invoke-webrequest這兩個命令。前者主要是獲取Json格式的內容,后者可以獲取整個網頁的內容。
比如說我希望查詢明天悉尼的天氣如何。網上隨便搜了一個提供API的站點
http://openweathermap.org/current#name
我打算搜索悉尼的,那么對應的格式是
http://api.openweathermap.org/data/2.5/weather?q=sydney,au他會自動生成一個Json格式的結果。
我們可以用invoke-restmethod直接獲取這個結果,比如說
$b=invoke-restmethod "http://api.openweathermap.org/data/2.5/weather?q=sydney,au" $c=[pscustomobject]@{ 'Description'=$b.weather.description 'name'=$b.name 'windspeed'=$b.wind.speed }
我也可以直接使用invoke-webrequest抓取整個網頁的內容,然后從Json的格式轉換過來也是一樣的
$a= Invoke-WebRequest -Uri "http://api.openweathermap.org/data/2.5/weather?q=sydney,au"$b=$a.Content | ConvertFrom-Json
類似的,如果我想獲取一個博客的RSS的最新內容。可以使用invoke-webrequest抓取對應的XML文件,比如
[xml]$a= Invoke-WebRequest -Uri "http://blogs.msdn.com/b/powershell/rss.aspx“$a.rss.channel.Item | select title,pubdate
功能很強大,使用卻很簡單。
本文出自 “麻婆豆腐” 博客
|
新聞熱點
疑難解答
圖片精選