PowerShellのスクリプトサンプル

PowerShellのスクリプトのサンプルとして、URLからRSSを読み込んでタイトル一覧を表示し、数字を入力するとその記事のテキストを表示する、まあ超貧弱版RSSリーダーといったものを作ってみました。
実用性はほとんどないですが、PowerShellのスクリプトがどういうものなのかというのは感じ取っていただけると思います。

#RSSを読み込んで記事を表示
#利用法:path¥rsstest.ps1 [URL] [RSSバージョン] [RSSの文字エンコード] [記事の文字エンコード]
#ex.(PC watch):.¥rsstest.ps1 http://pc.watch.impress.co.jp/sublink/pc.rdf 1.0 UTF-8 shift_jis | more
param($url, $rssVer = "1.0", $rssEnc = "UTF-8", $linkEnc = "UTF-8")
process {
  $wc = New-Object Net.WebClient
  $wc.Encoding = [System.Text.Encoding]::GetEncoding($rssEnc)
  $doc = [XML] $wc.DownloadString($url)
  $count = 0
  $link=@{}
  If($rssVer -eq "1.0"){
    $items = $doc.RDF.item
  } else {
    $items = $doc.rss.channel.item
  }
  ForEach($item in $items){
    Write-Host "[$count]: " + $item.title
    $link.[string] $count = $item.link
    $count++
  }
  $num = Read-Host "Select no."
  If($link.contains([string] $num)){
    $wc.Encoding = [System.Text.Encoding]::GetEncoding($linkEnc)
    $wc.DownloadString($link.[string] $num) -replace "<.*?>","" -replace "[ ¥t]¥n","" -replace "[¥n¥r][¥n¥r]+","`r`n"
  }
}

スクリプトを短くするため、パラメータのチェックなど厳密な処理は全く行っておりませんのであしからず。

 


    サイト内検索

    プロフィール

  • 顔絵
  • kotani(こたに)

    30台後半になって突然脱サラ。フリーのスクリプト系プログラマーとして独立を目論む謎のおやぢ。東京都在住。趣味は古本屋巡り、文具いぢり、機械いぢり、B級グルメ探索等々多岐にわたる。PCを使う作業に関しては何でもかんでも自動化したがる自動化オタク。