new-blogentry -topic "Powershell and More"

My observations about Powershell, Windows, System Center and life.

Recent comments

Tags

Don't show

    Disclaimer

    Any opinions expressed herein are completely accidental. But if one happens to slip in, it represents my own personal opinion and NO one elses. I'm also not concerned with changing anyone elses opinion, so any rants about anything presented on this site are likely to be 100% ignored.

    © Copyright 2010

    Powershell Syntax Highlighting

    Over on Lee Holmes' blog, he presented a very nice demonstration of a new feature in the CTP of Powershell V2 that allows for tokenization of the powershell syntax. Using this, he presented code that is able to colorize the syntax of a powershell script.

    I took his work and modified it to output to HTML for posting colorized bits of code into my blog entries. I was able to take out a bit of extra code since I don't have the complexity of dealing with the console. I just want to colorize each token appropriately for HTML. Here's the modified script presented in all it's colorized glory.

    Download Link: Get-SourceAsHTML.ps1 (2.61 kb)

     

    #requires -version 2.0
    # Original script from Lee Holmes
    # http://www.leeholmes.com/blog/SyntaxHighlightingInPowerShell.aspx
    # Modified by Gaurhoth for output to HTML
    function Get-SourceAsHTML {
        param([string]$filename,[switch]$passthru)
        # Two options for output
        #   1) DEFAULT: output is to clipboard if PSCX is installed.
        #   2) HTML is output through the pipeline as a string (if PSCX
        #      is not installed or -passthru is used).
        # Input is via specifying a filename or Clipboard (if PSCX is installed).

        # Test for PSCX
        if ((gcm Get-Clipboard).PSSnapIn.Name -eq 'Pscx') {
            $pscx_installed = $TRUE
        } else {
            $pscx_installed = $FALSE
        }

        if ($filename) {
            $file = (Resolve-Path $filename).Path
            $content = [IO.File]::ReadAllText($file) -replace "`t","    "
        } else {
            if ($pscx_installed) {
                $content = $(Get-Clipboard) -replace "`t", "    "
            } else {
                Throw "You must specify a filename."
            }
        }

        ## Read the text of the file, and parse it
        $parsed = [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) |
            Sort StartLine,StartColumn

        $replacementColours = @{
            "Attribute"="#8B4513";
            "Command"="#5F9EA0";
            "CommandArgument"="#0000FF";
            "CommandParameter"="#8B4513";
            "Comment"="#008000";
            "Grouper"="#000000";
            "GroupEnd"="#000000";
            "GroupStart"="#000000";
            "Keyword"="#0000FF";
            "Member"="#8B4513";
            "Number"="#000000";
            "Operator"="#FF0000";
            "Property"="#8B4513";
            "StatementSeparator"="#000000";
            "String"="#000000";
            "Type"="#0000FF";
            "Variable"="#800080";
        }

        $s = New-Object system.Text.StringBuilder

        $column = 1
        foreach($token in $parsed) {

            ## Determine the highlighting colour
            $color = $replacementColours[[string]$token.Type]
            if(-not $color) { $color = "#000000" }

            ## Now output the token
            if(($token.Type -eq "NewLine") -or ($token.Type -eq "LineContinuation")) {
                $column = 1
                [void]$s.AppendLine('<br />')
            } else {
                ## Do any indenting
                if($column -lt $token.StartColumn) {
                    [void]$s.Append( ("&nbsp;"*($token.StartColumn - $column) ))
                }

                ## See where the token ends
                $tokenEnd = $token.Start + $token.Length - 1

                [void]$s.Append("<span style=`"color: $color;`">")
                $line = -join $content[$token.Start..$tokenEnd]
                $line = [system.Web.HttpUtility]::HtmlEncode($line)
                $line = $line -replace '  ','&nbsp;&nbsp;'
                [void]$s.append($line)
                [void]$s.Append("</span>")

                ## Update our position in the column
                $column = $token.EndColumn
            }
        }

        if ($passthru -or (-not $pscx_installed)) {
            "<font face=`"Courier New`" size=`"2`">$($s.tostring())</font>" | write-output
        } else {
            "<font face=`"Courier New`" size=`"2`">$($s.tostring())</font>" | Out-Clipboard
        }
    }

    Posted by gaurhoth on Sunday, March 30, 2008 10:44 AM
    E-mail | Permalink | Comments (26) | Post RSSRSS comment feed

    Managing Podcasts with Powershell (Part 1)

    I've never before embraced the idea of listening to podcasts on a regular basis. With the recent purchase of an MP3 Player, it's garnered more of my interest. Unfortunately, I haven't stumbled on an automated approach to manage getting the downloaded podcasts synced to my player. I'm a creature of great laziness and would quickly lose interest in podcasts unless I find a way dump new episodes to my player with as little effort as possible.

    I could probably find a client somewhere (iTunes? WinAmp?)... but what fun would that be?

    I decided to play with the built in RSS Platform that's included as a part of Internet Explorer 7 (as such, IE 7 must be installed on your system). The RSS Platform includes a COM object which we can utilize from Powershell with ease. You could also use the FEED provider from PSCX if you chose.

    Once you subscribe to the feed using IE7, view the Feed Properties and make sure you have the 'Automatically download attached files' option checked and set a reasonable limit for 'Keep the most recent items only'. I set my limit at 3 items. Keep in mind that if you totally automate this as I have, every podcast will be synchronized to your MP3 device which may have limited space.

    feed01

    Give the system some time to download your enclosures in the background.

    Now, we run into the downside of using IE7's RSS Platform. It stores the enclosures in an obscure folder under the Temporary Internet Files. Let's take a peek at the object that will let us dive into the RSS Platform and find these mysterious enclosure folders.

    $feeds = (New-Object -ComObject Microsoft.FeedsManager).RootFolder
    $feedpodcast = $feeds.GetSubfolder('Podcasts')

    I store all of my Podcasts in a folder off the root of the FEED listing called 'Podcasts'. The second line is getting the object that represents that level of feed listings.

    We can get a list of all feeds in this folder using this:

    66> $feedpodcast.feeds
    Type     Name                                             ItemCount UnreadItemCount
    ----     ----                                             --------- ---------------
    feed     Adventures of Superman Podcast                          47               0
    feed     Batman Adventures                                       25               0
    feed     British Science Fiction Podcast                          3               0
    feed     Hanselminutes                                            3               0
    feed     Mind Of Root                                             3               0
    feed     PowerScripting Podcast                                   3               0
    feed     PowerShell Basics                                        3               0
    feed     Science Fiction Theater Podcast                         58               0
    feed     Scifi Friday                                             3               0
    feed     X Minus One Podcast                                     46               0
    feed     .NET Rocks!                                              3               0
    67> 

    Now, let's find the enclosure path:

    84> $($feedpodcast.feeds)[5]  | fl Name,Url,LocalEnclosurePath,DownloadEnclosuresAut
    omatically
    
    
    Name                            : PowerScripting Podcast
    Url                             : http://feeds.feedburner.com/Powerscripting
    LocalEnclosurePath              : C:\Users\gaurhoth\AppData\Local\Microsoft\Window
                                      s\Temporary Internet Files\Enclosure\{1BA818DF-D3
                                      C1-447D-A57F-8097CD250521}
    DownloadEnclosuresAutomatically : True
    
    
    
    85> 

    Now we know where to find the downloaded podcast files. Whew. Armed with this, we'll be able to write a script that will tie in all of these Enclosure Paths into a single parent folder so that Windows Media Player can monitor and sync to my player. I'll save that for the next part.

    Gaurhoth


    Posted by gaurhoth on Saturday, March 29, 2008 7:47 PM
    E-mail | Permalink | Comments (20) | Post RSSRSS comment feed

    A Long Silence

    After a longer silence than I had planned, I'm back with a new blogging home and a few ideas for new posts and content. I've also been experimenting with different blog engines and have delayed my re-appearence until I settled on something. My previous blog site (http://thepowershellguy.com/blogs/gaurhoth/) can be considered closed permanently. Please point your feed readers to the new location here.

    You'll notice some posts entries showing up with older dates starting to popup as I republish some of the more relevant posts to the new site.

    If you've just stumbled across my blog and want to find out a little more about me, check out the About Me page.

    gaurhoth


    Posted by gaurhoth on Saturday, March 22, 2008 5:30 PM
    E-mail | Permalink | Comments (41) | Post RSSRSS comment feed