Did you know that you can literally do anything in PowerShell that you can do in dotNET? To facilitate this point, here is a neat way to call the dotNET object System.Windows.Controls.MediaElement and play back a media stream. There are still thousands of shoutcast and icecast streams out there still today, just waiting for you to tap into them!

The example code below:

  • A new media object is created via New-Object
  • The media source is set to the applicable stream url
  • The default behaviur is set (unloaded)
  • $media.Play() plays the media object
  • $media.Stop() stops the media object
  • For good measure, we have added a quick curl command (note: curl is an alias for Invoke-WebRequest, you can check via Get-Alias curl) to grab and output song titles every 30 seconds.
### Real Punk Radio! ###
Add-Type -AssemblyName PresentationFramework
$media=New-Object System.Windows.Controls.MediaElement
$media.Source='http://149.56.155.73:8080'
$media.UnloadedBehavior='Manual'
$media.time
$media.Play()
for($i = 0 -lt 1)
{
    $curl = (curl ($media.Source.AbsoluteUri) -method Get)
    $parse = $curl.ParsedHtml.body.innerText.Split("`n") | Select-String "Playing Now"
    $parse = $parse -replace "\d\d:\d\d:\d\d", "" -replace "Playing Now: ", ""
    Write-Host (Get-Date -Format hh:mmtt), $parse
    SLEEP 30
}
## to stop: $media.Stop()

Note that a slight modification is needed if you are using PS7+ due to the changes there where curl/Invoke-WebRequest no longer has a .ParsedHtml method ($media | Get-Member). If you want to validate what version of PowerShell you are using, you can always check via: $PSVersionTable. From there you can instead key off of values in .Content or .RawContent (visible by default output <Enter> for $curl -or- $curl | Get-Member):

Other notable sources mention utilizing an HTML agility pack, Angle Sharp or an alternative 3rd party solution. For our scenario here, we will make some minor changes to our code (including the url we curl to in order to grab song info) and achieve the same end result with some additional regex/replace commands:

### Real Punk Radio! ###
Add-Type -AssemblyName PresentationFramework
$media=New-Object System.Windows.Controls.MediaElement
$media.Source='http://149.56.155.73:8080'
$media.UnloadedBehavior='Manual'
$media.time
$media.Play()
for($i = 0 -lt 1)
{
    $curl = (Invoke-WebRequest ($media.Source.AbsoluteUri) -method Get)
    $parse = ($curl.Content | Select-String "Playing Now.*\</a\>\</b\>\</td").Matches.Value
    $parse = $parse -replace "\</td\>\<td\>\<b\>\<a href=`"currentsong\?sid=1`">", "" -replace "Playing Now: ", ""
    $parse = $parse -replace "\</a\>\</b\>\</td", ""
    Write-Host (Get-Date -Format hh:mmtt), $parse
    SLEEP 30
}
## to stop: $media.Stop()

Leave a Reply

Your email address will not be published. Required fields are marked *