PowerShellからはてなAPIを呼び出す 1
なんかムショウにPowerShellからWebサービスを使いたくなったので、身近なところではてなの「ブックマーク件数取得API」を呼び出してみた。
XML-RPCというプロトコルで呼び出す必要があるらしく、聞いた事はあるけど使った事が無いのでとりあえず調べる。
↓このサイトを見たらだいたいわかった。
XML-RPC仕様書
ということで
完成したのが以下のスクリプト(Get-HateBuCount.ps1)
param([string[]]$siteURLs=@()) if($siteURLs.Length -eq 0 -or $args[0] -eq "-?") { $commandName = [IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name) Write-Host @" 説明: 指定したURLのサイトのはてなブックマーク数を取得します。 用法: $commandName siteURLs 注意: New-PSObject が必要です。 "@ -foregroundColor Yellow exit 1 } # XML-RPCリクエスト用 $reqXml = &{ @" <?xml version="1.0" encoding="UTF-8"?> <methodCall> <methodName>bookmark.getCount</methodName> <params> "@ $siteURLs | % { $siteURL=$_ @" <param><value><string>$siteURL</string></value></param> "@ } @" </params> </methodCall> "@ } $content = [Text.Encoding]::UTF8.GetBytes($reqXml) $httpReq = [Net.HttpWebRequest]::Create("http://b.hatena.ne.jp/xmlrpc") $httpReq.Method = "POST" $httpReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)" $httpReq.ContentType = "text/xml" $httpReq.ContentLength = $content.Length $reqStream = $httpReq.GetRequestStream() $reqStream.Write($content, 0, $content.Length) $reqStream.Close() $httpRes = $httpReq.GetResponse() if($httpRes.StatusCode -ne "OK") { Write-Error "レスポンスの取得中に問題が発生しました。" exit 1 } $resStream = $httpRes.GetResponseStream() $resXml = [xml]((New-Object IO.StreamReader($resStream)).ReadToEnd()) $resStream.Close() $resXml.methodResponse.params.param.value.struct.member | % { New-PSObject @{ Name=$_.name; Value=$_.value.int } }
param([Hashtable]$props=@{}) if($args[0] -eq "-?") { $commandName = [IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name) Write-Host @" 説明: PSObjectを作成します。 用法: $commandName [props=@{}] "@ -foregroundColor Yellow exit 1 } $obj = New-Object PSObject $props.GetEnumerator() | % { $obj | Add-Member NoteProperty $_.Key $_.Value } $obj
使い方はこんな感じ
PS > Get-HateBuCount http://www.google.co.jp, http://d.hatena.ne.jp Value Name ----- ---- 0 http://d.hatena.ne.jp 8 http://www.google.co.jp
XML-RPCはなかなかおもしろいので、そのうちこれ用の汎用的なスクリプトを作ってみようかな。
ちなみに最近スクリプトの書き方を↓この方のマネをして変えてみた。なんかいい感じ。
炎の作品 ― flamework.net ― | こちらは「.NET Framework」ではありません。「flamework.net」です。