PowerShell Cookbook

Search

Categories

 

On this page

Scripting Network / TCP Connections in PowerShell
PowerShell Prompt Here PowerToy
Download the Official Windows PowerShell 1.0 Release!
A New Virtual Earth Mashup in Born
Mathematical Pumpkins

Archive

Blogroll

Disclaimer
I work for Microsoft.

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 211
This Year: 11
This Month: 0
This Week: 0
Comments: 521

Sign In

 Wednesday, November 29, 2006
Thursday, November 30, 2006 2:04:06 AM (Pacific Standard Time, UTC-08:00) ( )

Awhile back, I introduced a script that allows you interact with remote TCP ports (such as Telnet.) While useful, it worked only interactively. It would be even more useful if you were able to script a network or TCP connection.

Let me introduce Connect-Computer.ps1 v2, which allows exactly that:

First, a simple scripted HTTP session:

$http = @"
GET / HTTP/1.1
Host:search.msn.com
`n`n
"@

$http | Connect-Computer search.msn.com 80

 

Second, a scripted POP3 session (Parse-TextObject comes from here: http://www.leeholmes.com/blog/parsetextObjectAWKWithAVengeance.aspx):

if(-not (test-path Variable:\mailCredential))
{
   $mailCredential = Get-Credential
}
$address = $mailCredential.UserName
$password = $mailCredential.GetNetworkCredential().Password
$pop3Commands = "USER $address","PASS $password","STAT","QUIT"
$output = $pop3Commands | Connect-Computer mail.leeholmes.com 110
$inbox = $output.Split("`n")[3]
$status = $inbox | Parse-TextObject -PropertyName "Response","Waiting","BytesTotal","Extra"
"{0} messages waiting, totaling {1} bytes." -f $status.Waiting,$status.BytesTotal

 

Now, here is Connect-Computer.ps1

## Connect-Computer.ps1
## Interact with a service on a remote TCP port
param(
        [string] $remoteHost = "localhost",
        [int] $port = 80,
        [string] $inputObject,
        [int] $commandDelay = 100
     )

[string] $output = ""

$currentInput = $inputObject
if(-not $currentInput)
{
    $SCRIPT:currentInput = @($input)
}
$scriptedMode = [bool] $currentInput

function Main
{
    ## Open the socket, and connect to the computer on the specified port
    if(-not $scriptedMode)
    {
        write-host "Connecting to $remoteHost on port $port"
    }

    trap { throw "Could not connect to remote computer: $_"; exit }
    $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)

    if(-not $scriptedMode)
    {
        write-host "Connected.  Press ^D followed by [ENTER] to exit.`n"
    }

    $stream = $socket.GetStream()
    $writer = new-object System.IO.StreamWriter($stream)

    ## Create a buffer to receive the response
    $buffer = new-object System.Byte[] 1024
    $encoding = new-object System.Text.AsciiEncoding


    while($true)
    {
        ## Receive the output that has buffered so far
        $SCRIPT:output += GetOutput

        ## If we're in scripted mode, send the commands,
        ## receive the output, and exit.
        if($scriptedMode)
        {
            foreach($line in $currentInput)
            {
                $writer.WriteLine($line)
                $writer.Flush()
                Start-Sleep -m $commandDelay
            }

            $SCRIPT:output += GetOutput

            break
        }
        ## If we're in interactive mode, write the buffered
        ## output, and respond to input.
        else
        {
            if($output) 
            {
                foreach($line in $output.Split("`n"))
                {
                    write-host $line
                }
                $SCRIPT:output = ""
            }

            ## Read the user's command, quitting if they hit ^D
            $command = read-host
            if($command -eq ([char4)) { break; }

            ## Otherwise, Write their command to the remote host     
            $writer.WriteLine($command)
            $writer.Flush()
        }
    }

    ## Close the streams
    $writer.Close()
    $stream.Close()

    ## If we're in scripted mode, return the output
    if($scriptedMode)
    {
        $output
    }
}

## Read output from a remote host
function GetOutput
{
    $outputBuffer = ""
    $foundMore = $false 

    ## Read all the data available from the stream, writing it to the
    ## output buffer when done.
    do
    {
        ## Allow data to buffer for a bit
        start-sleep -m 1000

        ## Read what data is available
        $foundmore = $false
        while($stream.DataAvailable) 
        {
            $read = $stream.Read($buffer, 01024)   
            $outputBuffer += ($encoding.GetString($buffer, 0, $read)) 
            $foundmore = $true
        }
    } while($foundmore)

    $outputBuffer
}

. main
[Edit: Thanks to Marco for pointing out a few issues that come up when you try to retrieve massive amounts of data (such as a newsgroup listing). I've updated the script to fix those.]
Comments [2] | | # 
 Monday, November 20, 2006
Monday, November 20, 2006 9:12:44 PM (Pacific Standard Time, UTC-08:00) ( )

Today, we have a guest post from Michael Murgolo. He's developed a PowerShell Prompt Here powertoy (like the one we all know and love,) but this one doesn't suffer from the uninstall bug that the current CMD Prompt Here powertoy (or its derivatives) do. And the explanation is awesome, to boot.

 

An Old PowerToy is New Again

by Michael Murgolo

PowerShell PowerToys Download

One of the most popular Windows PowerToys is the venerable Command (or CMD) Prompt Here.  This PowerToy is still available as part of the Microsoft PowerToys for Windows XP or the Windows Server 2003 Resource Kit Tools.  With this PowerToy installed, you can right click on a folder or drive in Windows Explorer and select CMD Prompt Here from the context menu.  This will open a command prompt with the selected folder as the current directory.

Because this is so handy, I use this PowerToy numerous times as day.  As I was trying to learn and use Windows PowerShell, I found myself wishing for the same functionality in PowerShell.  So I grabbed the Setup Information (INF) File for CMD Prompt Here, cmdhere.inf, from the Windows Server 2003 Resource Kit Tools and modified it to create a PowerShell Prompt Here context menu.  This INF file is included in the PowerShell PowerToys Download.  To install it, right click on the INF file and select Install.

In the course of creating the PowerShell version, I discovered that the original CMD Prompt Here PowerToy had a bug that would leave behind a dead context menu entry when it was uninstalled.  I have provided an updated version of cmdhere.inf for you convenience also in the PowerShell PowerToys Download. 

How it works

Both of these PowerToys take advantage of the fact that these context menu entries are configured in the Windows Registry under keys associated with the Directory and Drive object type.  This is done in the same way that context menu actions are associated with file types.

For example, when you right click on a .txt file in Explorer, you get several actions at the top of the list like Open, Print, and Edit.  To find out how these items are configured, let’s take a short journey through the HKEY_CLASSES_ROOT Registry hive.  If you open the Registry Editor and expand the HKEY_CLASSES_ROOT branch you will see keys that are named for file types like .doc, .txt, etc.  If you click on the .txt key, you will see the (Default) value is txtfile.

This is the object type associated with a .txt file.  If you scroll down and expand the txtfile key, then expand the shell key under that, you will see keys named for some of the context menu entries for a .txt file.  (You will not see all of them because there are other methods for creating context menus.)  Under each of these is a command key.  The (Default) value under the command key is the command line that Windows executes when you select that context menu item.

The PowerToys for both the CMD prompt and PowerShell prompt use this technique to configure the CMD Prompt Here and PowerShell Prompt Here context menu entries. There are no file types associated with drives and directories, but there is a Drive and a Directory key under HKEY_CLASSES_ROOT associated with those object types.

The PowerShellHere.ps1 script (in the attached file) shows how to set the same Registry entries as PowerShellHere.inf. This can be used in the case where an entry is Add/Remove Programs to uninstall the PowerToy is not desired.

To remove these entries you can use RemovePowerShellHere.ps1, also included in the PowerShell PowerToys Download.

  

 

Michael Murgolo is a Senior Infrastructure Consultant for Microsoft Consulting Services. He is focused in the areas of operating systems, deployment, network services, active directory, systems management, automation, and patch management.

Comments [4] | | # 
 Tuesday, November 14, 2006
Tuesday, November 14, 2006 10:37:33 AM (Pacific Standard Time, UTC-08:00) ( )

A few minutes ago, Bob Muglia and Jeffrey Snover at IT Forum announced something at we've long been waiting for – the official Release to Web (RTW) of Windows PowerShell v1.0!

In late December of 2002, PowerShell entered the public eye when a Slashdot reader stumbled upon a job posting for "Microsoft's Next Generation Shell". About a year later, we officially announced the project (code-named "Monad") at the 2003 Microsoft Professional Developer's Conference. Things started to really pick up steam when we released our first really public preview in September of 2004 – a fact not missed by the ever vigilant Slashdot.
Since then, we've shipped incremental previews frequently, gaining enormous benefit from all of you – a passionate and active community of devoted beta enthusiasts:

"Monad" Beta 1 - 06/17/2005
"Monad" Beta 2 - 09/13/2005
"Monad" Beta 3 - 01/10/2006
"Monad" Beta 3.1 - 03/09/2006
Windows PowerShell RC1 - 04/25/2006
Windows PowerShell RC2 - 09/27/2006
Windows PowerShell RTW – 11/14/2006

Each release added features, fixed bugs, and incorporated heaps of changes initiated by feedback from the community.

This has been a long and adventurous journey – something that's truly been worth relishing. Whether you are an old or new participant in the PowerShell community, you should feel proud of your contributions – and for a job well done.

You can find pointers to the official release at http://www.microsoft.com/powershell -- so go install it, and enjoy the revolution!

Comments [6] | | # 
 Thursday, November 09, 2006
Thursday, November 09, 2006 8:28:08 AM (Pacific Standard Time, UTC-08:00) ( )

About 8 months ago, I wrote a Virtual Earth mashup to display commute times to Microsoft in and around the Seattle area. It's been very successful, and solves a big problem for many people looking to buy a house (amongst other things.)


http://www.leeholmes.com/projects/commute

About 3 or 4 months after posting the mashup, the Virtual Earth team changed a bunch of the APIs, which pretty much broke every existing mashup – including mine. I patched it up a bit some time later, but couldn't spend the time to fully restore its functionality. For example, the zooming controls were broken, as were the panning controls.

Neither writing the mashup (nor living through the breaking changes) were terribly pleasant experiences. The Virtual Earth map control was simply too basic. With not much effort, you get a map that scrolls, but nothing else. No UI, no support for panning, zooming, or anything else.

Want to make it interactive and snazzy? In my case, that meant copying tons of Virtual Earth infrastructure scripts, html, images, and other random junk in order to make something presentable.

However, the end result was definitely exciting despite all of that.

I checked on the APIs tonight to get a gauge on how much work was in front of me to fix it completely again, and was stunned. The Virtual Earth team has done a truly amazing job at focusing on making the job of a "masher" as easy as possible. Their programming model has matured significantly, placing a much cleaner boundary between your application and the Virtual Earth implementation details. It feels like a real API now, as opposed to forcing you into an invasive, parasitic implementation.

One innovation I'm immensely impressed with is their new interactive SDK. It takes cues from the cookbook / task-based approach to learning. First, you click on a node to say, "I want to --> Use pushpins --> Add a custom pushpin." Then, the SDK shows you – through an interactive working view, example code, and reference page -- exactly how to do it.

In the end, I didn't patch my old code back into working condition. I reused my support code, but rewrote the UI and interface to Virtual Earth again from scratch. In just a few hours I was done:

  • My index page has gone from 11k to 3k
  • My custom Javascript has gone from 6k to 5k
  • My entire project has shrunk from 391kb to 71kb
  • That furrow in my brow is gone

Kudos to the Virtual Earth team. The mashup experience is definitely a first-class citizen, and it shows.

Comments [0] | | # 
 Thursday, November 02, 2006
Thursday, November 02, 2006 7:22:44 AM (Pacific Daylight Time, UTC-07:00) ( )

Well, last night was Halloween, where I got the chance to enjoy the eerie glow of our scary pumpkin.  Well, scary if you don't like fractals, that is.

Last year, we carved out a Sierpinski Triangle -- which surprisingly only took a toothpick or two to repair isolated triangles:

This year, I wanted to stay with the fractal theme. I didn't necessarily want to attempt the Julia or Mandelbrot sets, so instead did a Sierpinski Carpet (along with a wee bit of evil, of course:)

 

Not being one to cut 64 of the level-three squares by hand, a cordless drill came in extremely handy.

Unfortunately, when I'm out trick-or-treating, there's nobody around to give candy to the little monsters.  I leave a note above a bowl on a chair -- this year, I finally realized why my calligraphy pens include red in the set!

 

Comments [0] | | #