Search-Twitter.ps1 1.43 KB
Newer Older
O'Reilly Media, Inc.'s avatar
O'Reilly Media, Inc. committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
##############################################################################
##
## Search-Twitter
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Search Twitter for recent mentions of a search term

.EXAMPLE

Search-Twitter PowerShell
Searches Twitter for the term "PowerShell"

#>

param(
    ## The term to search for
    $Pattern = "PowerShell"
)

Set-StrictMode -Version Latest

## Create the URL that contains the Twitter search results
Add-Type -Assembly System.Web
$queryUrl = 'http://integratedsearch.twitter.com/search.html?q={0}'
$queryUrl = $queryUrl -f ([System.Web.HttpUtility]::UrlEncode($pattern))

## Download the web page
$wc = New-Object System.Net.WebClient
$wc.Encoding = [System.Text.Encoding]::UTF8
$results = $wc.DownloadString($queryUrl)

## Extract the text of the messages, which are contained in
## segments that look like "<div class='msg'>...</div>"
$matches = $results |
    Select-String -Pattern '(?s)<div[^>]*msg[^>]*>.*?</div>' -AllMatches

foreach($match in $matches.Matches)
{
    ## Replace anything in angle brackets with an empty string,
    ## leaving just plain text remaining.
    $tweet = $match.Value -replace '<[^>]*>', ''

    ## Output the text
    [System.Web.HttpUtility]::HtmlDecode($tweet.Trim()) + "`n"
}