More servicesWindows Live
HomeHotmailSpacesOneCare
 
MSN
Sign in
 
 
Spaces home  Time is an illusion. Lun...PhotosProfileFriendsBlog Tools Explore the Spaces community

Blog

October 15

And now for a little Rossini

More music performed by the 1978 PCC Chamber Singers.  This time it's a little Rossini:
Accompanied again by Twyla Meyer and the soprano (heard around 4:20) is the spectacular Rebecca Sherburn.  This group was really quite impressive, I know that a number of the singers in this group have careers as singers.   Twyla is in great demand throughout LA and Bill Hatcher has had stellar career in choral music.  I feel extremely fortunate that I had the opportunity to learn from these amazing musicians.
October 11

more from PCC - 1978

Audite Nova by Lassus this time - it's a very silly piece. 
 
I remember really liking this piece and having a great time performing it.  Listening to it now, it seems so heavy, i suppose it should, with 6 on a part.  I've performed and listened to so much one-on-a-part that it's clear how much I've changed in the past 30 years.  Thank goodness for that - it would be horrible to think that I hadn't changed.
 
I've got a few more of these and also some recordings of the Pasadena Chorale from around 79 to 83.  I'll get them posted after I finish the Chamber Singers stuff
 
 
 
 
 
August 31

I love Twitter

I love the idea of twitter - I think it's the logical intersection between blogging and reduced attention spans.  I started to play about with it and I was frustrated with the way I needed to create entries.  Having a separate app to create twitter updates seemed wrong to me.  I don't want to change focus from my current shell to create an update and best case, I want to update my status automatically so I don't think about it, it just happens. 
 
I know that there are some command line tools to do this, but I I want a native solution for PowerShell, so I created a Send-TwitterStatus cmdlet to allow me to send updates directly from my shell.  Not only that, but I can use this cmdlet in other scripts to automatically push my activity to Twitter as well.  I created media player script and it seems like a natural thing to do is to push my playlist to Twitter so my friends can see what I'm listening to (if they want).  I have a line now in the script when I append an album to my playlist is a line that calls my cmdlet and pushes my update:
 
   Send-TwitterStatus "Adding to office playlist: $album" $credential
 
  • $album is the name of the album
  • $credential is a global variable that contains a PSCredential which is used by the cmdlet to authenticate with the Twitter service.  
I grabbed the Yedda.Twitter code to do the actual Twitter interaction and the rest is just the code to stitch the cmdlet together.  I also convert the XML results into a custom object so I can eventually create the appropriate formatting. 
 
Anyway - here you go. 
 
and the cmdlet code
My post http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!119.entry will show how to compile and install a snapin and use.
 
Next steps are to create the various twitter getters and create the format file so I can get activity directly from the shell.
 
 
 
 

More media - PCC Chamber Singers, 1978

It seems like the time just flies - it's been a couple months since I updated here, and I would like to post more often. 
 
In any event, I have another audio file to post!  This is the third of the Trois Chanson Britonnes Soir d'été.  My memory of the recording circumstances is a little fuzzy, since it was nearly 30 years ago, but I seem to remember that we did this recording around the end of the calendar year, and we hadn't yet learned the second chanson, so I only have this one (the last) and the first.
 
Conducted by Bill Hatcher and accompanied by the magnificent Twyla Meyer .
 
Here it is: Soir d'été
 
Some of the other pieces from this recording session are:
  • Audite Nova
  • I Heard a Voice
  • Deck the Halls
There are more, and I'll post them as I can
 
July 15

Tracing the script stack

It's not uncommon that after I've created a fairly complicated script after a while of using it, something bad happens that I wasn't expecting. And I would really like to know how I got to this state, so a stacktrace of my script would be really, really nice. Sadly, this isn't something that is a default behavior or PowerShell, but fortunately, this sort of thing is actually possible to do with just a little bit of script!

Most of the real world examples are more complicated than we really need to use to illuminate the problem.  So, I've created a simple example that is useful for discussion.

Take the following script:
# test-stacktrace1.ps1
param ( $startVal )
function func1
{
    param ( $startVal )
    1/$startVal--
    func2 $startVal
}
function func2
{
    param ( $startVal )
    1/$startVal--
    func3 $startVal
}
function func3
{
    param ( $startVal )
    1/$startVal--
}
func1 $startVal

When I run this script, depending on the value of my argument, the script will run or fail:

PS# c:\temp\test-stacktrace 5
0.2
0.25
0.333333333333333
PS# c:\temp\test-stacktrace1 2
0.5
1

Attempted to divide by zero.
At c:\temp\test-stacktrace1.ps1:18 char:7
+     1/$ <<<< startVal--

The message is ok - it tells me that I had a problem on the appropriate line in the script, but I don't know how I got there by looking at the message.  What I would really like to see is both the error and the way I got there.  Here are some examples of what I want to see:

This example is the normal behavior
PS# c:\temp\test-stacktrace2 3
0.333333333333333
0.5
1

This example will show what happens when an error occurs deep in the stack:
PS# c:\temp\test-stacktrace2 2
0.5
1
func3 : Attempted to divide by zero.
At c:\temp\test-stacktrace2.ps1:25 char:10
+     func3  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:31 char:42+     trap { write-error $_; get-stacktrace  <<<< }
At c:\temp\test-stacktrace2.ps1:25 char:10+     func3  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:17 char:10+     func2  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:36 char:6+ func1  <<<< $startVal
At line:1 char:25+ c:\temp\test-stacktrace2  <<<< 2

Notice that I see the functions that I called on the way to this error - This way I can see the path of woe that generated the error - which means I have a much better chance of actually fixing the problem. 

Here's another example of what happens when an error occurs sooner in the stack, notice that we only see func1 and func2 calls:
PS# c:\temp\test-stacktrace2 1
1
func2 : Attempted to divide by zero.
At c:\temp\test-stacktrace2.ps1:17 char:10
+     func2  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:23 char:42+     trap { write-error $_; get-stacktrace  <<<< }
At c:\temp\test-stacktrace2.ps1:17 char:10+     func2  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:36 char:6+ func1  <<<< $startVal
At line:1 char:25+ c:\temp\test-stacktrace2  <<<< 1

And finally what happens when an error occurs right away, notice that we only see func1 in the stack:
PS# c:\temp\test-stacktrace2 0
func1 : Attempted to divide by zero.
At c:\temp\test-stacktrace2.ps1:36 char:6
+ func1  <<<< $startVal
At c:\temp\test-stacktrace2.ps1:15 char:42+     trap { write-error $_; get-stacktrace  <<<< }
At c:\temp\test-stacktrace2.ps1:36 char:6+ func1  <<<< $startVal
At line:1 char:25+ c:\temp\test-stacktrace2  <<<< 0

So, here's the code - and a brief discussion follows:

param ( $startVal )
function get-stacktrace
{
    trap { continue }
    1..100 | %{
        $inv = &{ gv -sc $_ myinvocation } 2>$null
        if ($inv) { write-host -for blue $inv.value.positionmessage.replace("`n","") }
        }
    exit
}
function func1
{
    param ( $startVal )
    trap { write-error $_; get-stacktrace }
    1/$startVal--
    func2 $startVal
}
function func2
{
    param ( $startVal )
    trap { write-error $_; get-stacktrace }
    1/$startVal--
    func3 $startVal
}
function func3
{
    param ( $startVal )
    trap { write-error $_; get-stacktrace }
    1/$startVal
}
# Main
func1 $startVal

Notice the addition of the "get-stacktrace" function:

function get-stacktrace
{
    trap { continue }
    1..100 | %{
        $inv = &{ gv -sc $_ myinvocation } 2>$null
        if ($inv) { write-host -for blue $inv.value.positionmessage.replace("`n","") }
        }
    exit
}
 

This function takes advantage of the fact that the PowerShell scoping rules allow you to inspect variables in different scopes from your current scope.  This isn't available via syntax, but it is available via the get-variable cmdlet (aliased to gv).  So our little get-stacktrace function just drills down our scopes looking for the myInvocation property which has the information about what line on the script we're on.  There are some other things that are going on.  The trap statement assures me that if I get any terminating errors that I ignore them and I've placed the call of gv in a script block - this allows me to really throw away any messages that get-variable may throw that aren't terminating errors.   Lastly, I want to be sure that my message is on a single line, so I replace the carriage returns with empty strings.

Notice also that each function now has a trap statement.  I think that this is generally good practice regardless, but these do two things.  First they write the error and then call the get-stacktrace function.  We need to write the error because the get-stacktrace function is going to exit, so if we didn't have this write-error we wouldn't actually see what the error was, just the stack trace which isn't enough info.

So, if you've got a complicated script and you would really like to discover how you got where you are, I hope this little bit of script will help!

Jim

 

June 22

Blasts from the past

Wow - I haven't written for a long time - however, I think I'll be doing more because while I was cleaning up my home office, I found a number of cassette tapes to which I've been hanging for an even longer time. 
I've been incredibly fortunate to perform with a number of very excellent ensembles over the years.  I found recordings dating back to when I I first started singing at Pasadena City College in 1976-78 - I'm going to be sharing them here in my blog so the folks can get access to them as I can convert them from tape to digital.
 
So, I'll try to reduce the noise, and do some of the usual mastering activities.  We'll see how successful I am at that, it will be a learning experience for me.  With the first one, I haven't done any noise reduction of mastering, it's just right off the tape, so you'll hear some tape hiss.  Also, as I recall, the recording was done by some pretty crummy omnidirectional mics (and I seem to remember that it was recorded on reel-to-reel, so this cassette might be a copy of that).  This is a recording from 1978 of the first movement of Trois Chanson by Henk Badings performed by the Pasadena City College Chamber Singers, conducted by Bill Hatcher who inspired me greatly and accompanied by the amazing Twyla Meyer.
 
Here you go: La Nuit En Mer
 
 
jim 
February 19

PowerShell Extended Types (includes a TYPES.XSD)

One of my favorite features of PowerShell is the extended type system.  This system allows us to extend the .NET objects that are returned by the underlying .NET framework with bits of interesting stuff.  There's two way to go about this.  First, by using the add-member cmdlet, it's possible to add methods and properties to an instance of an object.  If we start with a "blank" object, we can create an object out of whole cloth.  Take a look at the following output
 
PS> get-stock|ft Symbol,Last,Change,@{l="ChangeP";f="{0:N2}";e={$_.ChangeP}} -auto
Symbol     Last Change ChangeP
------     ---- ------ -------
MSFT      28.74  -0.72   -2.51
SCO        2.77  -0.02   -0.72
^DJI   12767.57   2.56    0.02
INFY      59.84   0.23    0.38
SUNW       6.29  -0.02   -0.32
 
I have a little script that collects the stock quotes for a number of companies.   (I have a special formatting file for the output, but that's another blog).  Here's the script, you can see how it takes advantage of the extendable type system. 
 
$SYMS = "MSFT","SCO","^DJI","INFY","SUNW"
$wc = new-object net.webclient
foreach ( $SYM in $SYMS )
{
    $yahoo = "
http://finance.yahoo.com/d/quotes.csv?s="
    $url = "${yahoo}${SYM}&f=sl1d1t1c1ohgv&e=.csv"
    $string = $wc.DownloadString($url)
    if ( $string )
    {
        trap { continue }
        $stock = $string.replace("`"","").replace("N/A","0").Trim().split(",")
        $obj = new-object System.Management.Automation.PSObject
        $obj.psobject.typenames[0] = "Custom.Stock"
        $obj | add-member NoteProperty Symbol  ([string]$stock[0])
        $obj | add-member NoteProperty Last    ([double]$stock[1])
        $obj | add-member NoteProperty Date    ([datetime]$stock[2])
        $obj | add-member NoteProperty Time    ([datetime]$stock[3])
        $obj | add-member NoteProperty Change  ([double]$stock[4])
        $obj | add-member NoteProperty ChangeP ([double]$stock[4]/[double]$stock[1] * 100)
        $obj | add-member NoteProperty Open    ([double]$stock[5])
        $obj | add-member NoteProperty High    ([double]$stock[6])
        $obj | add-member NoteProperty Low     ([double]$stock[7])
        $obj | add-member NoteProperty Volume  ([int]$stock[8])
        $obj | add-member NoteProperty InPort  ($pf -contains $SYM)
        $obj
    }
}
 
So, that's a way to use the add-member cmdlet to dynamically extend an object.   This could be done with any object, in this example, I'm creating an object out of nothing, but you can do the same thing with any object.  Here's another example, where I interact with some performance counters, specifically the idle time.
 
PS> $idle = get-idle
PS> $idle

CPUCount         : 2
Percent          : 100
CategoryName     : Process
CounterHelp      : % Processor Time is the percentage of elapsed time that all
                   of process threads used the processor to execution instructi
                   ons. An instruction is the basic unit of execution in a comp
                   uter, a thread is the object that executes instructions, and
                    a process is the object created when a program is run. Code
                    executed to handle some hardware interrupts and trap condit
                   ions are included in this count.
CounterName      : % Processor Time
CounterType      : Timer100Ns
InstanceLifetime : Global
InstanceName     : Idle
ReadOnly         : True
MachineName      : JIMTRUD4
RawValue         : 10053571562500
Site             :
Container        :
 
PS> $idle.getidle()     # I'll call my custom script method!
99
PS> $idle.getidle()
88                                        # the reason this fell so much is that I put some load on the system
PS> $idle.getidle()
90
Here's the script - I'm sure it could be written better, but that's not the point.
 
param ( $systems = @( $env:computername ))
$PerfCnt = "System.Diagnostics.PerformanceCounter"
$PerfCat = "System.Diagnostics.PerformanceCounterCategory"
foreach($system in $systems )
{
    $Info = "Process","% Processor Time","Idle",$system
    $obj = new-object $PerfCnt $Info
    $pcc = new-object $PerfCat Processor,$system
    $idColCol = $pcc.ReadCategory()
    [int]$CPUCount = $idColcol['% idle time'].keys.count - 1
    $per = $obj.nextvalue() / $CPUCount
    # for some reason, we need to sleep here and then check again
    # I haven't bothered to find out why
    sleep 1
    [int]$per = $obj.nextvalue() / $CPUCount
    # add some members to the the performance counter
    $obj | add-member NoteProperty CPUCount $CPUCount
    $obj | add-member NoteProperty Percent $per
    $obj | add-member ScriptMethod GetIdle {
        $this.Percent = [int]($this.NextValue() / $this.CPUCount)
        $this.Percent
        }
    # emit the object
    $obj
}
 
Viola!  I've extended the instances of the PerformanceCounter objects created in this script
 
However, there is another way to extend an object instance.  You can create a blob of XML (in a file) and then load that file into your session with the update-typedata cmdlet - whammo! - everytime you create an instance of a specific object, it will have your custom extensions.   We have a number of these extensions in the standard release to ease using the shell.  The best case in point is the difference between System.Array and System.Collections.ArrayList.  "Length" is the property in System.Array that provides the count of the elements of the array, but System.Collections.ArrayList uses "Count".  We extended the System.Array type with a "Count" property that is an alias to the Length property which actually exists.  This way, regardless of whether you've got an array or arraylist, "Count" will work!  Here's the blob of XML that does the trick.
 
<Types>
 <Type>
  <Name>System.Array</Name>
  <Members>
   <AliasProperty>
    <Name>Count</Name>
    <ReferencedMemberName>Length</ReferencedMemberName>
   </AliasProperty>
  </Members>
 </Type>
<Types>
 
Once you have this bit of XML in a file, you can use the update-typedata cmdlet to add the blob to your environment.  Let's make our own little extension so you can see how it works.
 
PS> cat mynewtype.ps1xml
<Types>
 <Type>
  <Name>System.Array</Name>
  <Members>
   <AliasProperty>
    <Name>HappyAlias</Name>
    <ReferencedMemberName>Length</ReferencedMemberName>
   </AliasProperty>
  </Members>
 </Type>
</Types>
 
As you can see, it's pretty simple.  Now let's load it:
 
PS> update-typedata mynewtype.ps1xml
PS> ,(1,2,3,4)|gm

   TypeName: System.Object[]
Name               MemberType    Definition
----               ----------    ----------
Count              AliasProperty Count = Length
HappyAlias         AliasProperty HappyAlias = Length
...
SyncRoot           Property      System.Object SyncRoot {get;}

PS> ,(1,2,3,4).happyalias
4
PS>
We've extended the array type!  However, figuring out what is possible isn't documented anywhere, so it's a little tricky to create these.  We allow all sorts of extensions; a bunch of different property extensions, methods (both script and code). With this in mind, I created an XSD that allows me to create types extensions much more easily.  Now I can edit my type extensions in Visual Studio and they nearly write themselves.  Note that this XSD may have some errors, and as time goes on, I'll correct it as I can.  However, in the mean time, it's better than a poke in the eye with a sharp stick.
 
I'm also working on an XSD for our formatting - stay tuned for that
 
 
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="
http://www.w3.org/2001/XMLSchema">
  <xs:element name="Name" type="xs:string" />
  <xs:complexType name="NoteProperty">
      <xs:all>
        <xs:element ref="Name" />
        <xs:element name="Value" type="xs:string" />
      </xs:all>
    </xs:complexType>
  <xs:complexType name="AliasProperty">
      <xs:all>
        <xs:element ref="Name" />
        <xs:element name="ReferencedMemberName" type="xs:string" />
      </xs:all>
    </xs:complexType>
  <xs:complexType name="ScriptMethod">
      <xs:all>
        <xs:element ref="Name" />
        <xs:element name="Script" type="xs:string" />
      </xs:all>
    </xs:complexType>
  <xs:complexType name="ScriptProperty">
      <xs:sequence>
        <xs:element minOccurs="1" maxOccurs="1" ref="Name" />
        <xs:element minOccurs="0" maxOccurs="1" name="GetScriptBlock" type="xs:string" />
        <xs:element minOccurs="0" maxOccurs="1" name="SetScriptBlock" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
 
  <xs:complexType name="CodeReference">
      <xs:all>
        <xs:element name="TypeName"/>
        <xs:element name="MethodName"/>
      </xs:all>
    </xs:complexType>
 
  <xs:complexType name="CodeMethod">
      <xs:sequence>
        <xs:element name="Name" type="xs:string"/>
        <xs:element name="CodeReference" type="CodeReference"/>
      </xs:sequence>
    </xs:complexType>
  <xs:complexType name="CodeProperty">
      <xs:all>
        <xs:element name="Name" type="xs:string" />
        <xs:element minOccurs="0" maxOccurs="1" name="GetCodeReference" type="CodeReference" />
        <xs:element minOccurs="0" maxOccurs="1" name="SetCodeReference" type="CodeReference" />
      </xs:all>
    </xs:complexType>
  <xs:complexType name="PropertySet">
      <xs:sequence>
       <xs:element ref="Name" />
       <xs:element name="ReferencedProperties" />
      </xs:sequence>
    </xs:complexType>
  <xs:complexType name="Members">
     <xs:sequence>
      <xs:choice maxOccurs="unbounded">
       <xs:element name="NoteProperty" type="NoteProperty" />
       <xs:element name="AliasProperty" type="AliasProperty" />
       <xs:element name="ScriptProperty" type="ScriptProperty" />
       <xs:element name="CodeProperty" type="CodeProperty" />
       <xs:element name="ScriptMethod" type="ScriptMethod" />
       <xs:element name="CodeMethod" type="CodeMethod" />
       <xs:element name="MemberSet" type="MemberSet" />
       <xs:element name="PropertySet" type="PropertySet" />
      </xs:choice>
     </xs:sequence>
   </xs:complexType>
 
  <xs:complexType name="MemberSet">
      <xs:all>
        <xs:element name="Name" type="xs:string"/>
        <xs:element name="Members" type="Members" />
      </xs:all>
  </xs:complexType>
 
  <xs:element name="Types">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Type">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Name" type="xs:string" />
              <xs:element name="Members" type="Members" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
 
I'm sorry about the length - i should learn to stop typing.
 
 
December 02

Getting more out of help

As we were developing PowerShell, we knew that we wanted to provide a capability for searching through the help. Unfortunately, we don't always get to everything, and this is one of those things that we couldn't get to.  However, I still sometimes need to search through the help, so I created this little function to do the search.  It searches through the conceptual topics for the string for which I'm looking and with the switch parameter "-all", I search through the descriptions of the cmdlet help as well.

Like most things in PowerShell, it turns out to be pretty simple.  Here's how I would look for help that has the word "process" in it, I use -all to retrieve cmdlet help in addition to the conceptural (about*) topics. 

PS> search-help process -all
 
HelpTopic                  Reference
---------                  ---------
about_arithmetic_operators The command then processes the parameters as it w...
about_array                .NET Framework. For example, the objects that Get...
about_assignment_operators current process. For example, the following comma...
about_automatic_variables  Contains objects for which an error occurred whil...
about_commonparameters     the command during processing. This variable is
about_environment_variable system path, the number of processors used by the...
about_filter               processes that begin with the letters a through m...
about_foreach              displays any processes whose working-set (memory ...
about_function             filters. The primary difference between the two i...
about_location             As a result, all commands are processed from this...
about_logical_operator     When PowerShell processes this statement, it eval...
about_object               receives the objects from the first command, proc...
about_operator             fact that PowerShell processes operators in a ver...
about_parsing              When processing a command, the PowerShell parser ...
about_pipeline             down the pipeline to the second command. The seco...
about_provider             Alias                ShouldProcess               ...
about_quoting_rules        is passed to the command for processing. Consider...
about_shell_variable       example, the $PID variable stores the process ID ...
about_signing              export process.
about_switch               The keyword "break" indicates that no more proces...
about_wildcard             in order to return specific results. The process ...
default                    get-help get-process   : Displays help about the ...
ForEach-Object             Performs an operation against each of a set of in...
Where-Object               Creates a filter that controls which objects will...
Get-Process                Gets the processes that are running on the local ...
Stop-Process               Stops one or more running processes.
Set-Content                Writes or replaces the content in an item with ne...
Export-Csv                 Creates a comma-separated values (CSV) file that ...
Sort-Object                Sorts objects by property values.
Get-TraceSource            Gets the Windows PowerShell components that are i...

Here’s the search-help script - as you can see, it's just a few lines.   The interesting bit is the use of Select-Object.  With Select-Object, I create custom objects from both about* help and cmdlet help.  Select-Object allows me to specify which properties I want, but it also allows me to "rename" the property.  This way I can take two disparate bits of information (the bits I get back from Select-String and the bits I get out of the help object) and create objects that will act consistently regardless of their origin.

function Search-Help
{
param ( $pattern, [switch]$all ) $path = “${pshome}\about*.txt” Select-String -list –pattern ${pattern} –path ${path}| select-object @{ n="HelpTopic"; e = {$_.filename -replace ".help.txt"}}, @{n="Reference";e={$_.line.trim()}} if ( $all ) { Get-Help * | where-object { $_.description -match ${pattern}}| select-object @{n="HelpTopic";e={$_.Name}}, @{n="Reference"; e={$_.synopsis}}
} }
I hope this is useful for you!
jim
October 16

Dijkstra

 

I recently received the following question:

Im  trying to solve the following problem in Powershell:

 I know the name of Active Directory Site A and the name of Active Directory Site B, Site A doesn’t necessarily have a site link to Site B (could go A -> C -> B). What is the total cost of the least cost path between these 2 sites? What is the total cost between any 2 sites? (effectively I’m trying to replace this : http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ad/ad/dsquerysitesbycost.asp api with a Powershell version.)

To do so, I think I need to implement some kind of Dijkstra engine  to solve this...

 Yay for Wikipedia (http://en.wikipedia.org/wiki/Dijkstra)!

 Bruce and I thought it might be fun to put this together – we took it straight from the C code.  Given the following graph

Where the weight of the path is written on the line.  Here’s the output from running the script:

PS> get-dijkstra
The distance between nodes 0 and 0 is 0
The distance between nodes 0 and 1 is 2
The distance between nodes 0 and 2 is 1
The distance between nodes 0 and 3 is 5
The distance between nodes 0 and 4 is 4
The distance between nodes 0 and 5 is 6
The distance between nodes 0 and 6 is 6
The distance between nodes 0 and 7 is 8

Showing that the shortest path is 8!  Unfortunately, this script doesn’t show the nodes in the path.  I’ll leave that as an exercise for the reader.  The real point of the exercise was to show the amount of effort that was needed to convert the C into PowerShell!  We basically had to create the structures in the C code, which we did via HashTables (and used functions to create the hashtables).

Here’s the script (again, a straight forward port of the C code from the Wiki site, it's basic but it works!):

### get-dijkstra.ps1
$INFINITY = [int]::MaxValue-1
function edge ([int] $weight, [int] $dest)
{
    @{weight = $weight; dest = $dest}
}

function Vertex( [object[]] $connections)
{
    @{
       connections = $connections; # An array of weighted arcs
       numconnect = $connections.length
       distance = $INFINITY
       isDead = $false
    }
}

function Dijkstra([object[]] $graph, [int] $source)
{
    [int] $nodecount = $graph.length
    $graph[$source].distance = 0
    for($i = 0; $i -lt $nodecount; $i++) {
        $min = $INFINITY+1
        # find the unchecked node closest to the source
        for($j = 0; $j -lt $nodecount; $j++) {
            if(! $graph[$j].isDead -and $graph[$j].distance -lt $min) {
                $next = $j
                $min = $graph[$j].distance
            }
        }
        # check all paths from node 
        for($j = 0; $j -lt $graph[$next].numconnect; $j++)
        {
            if($graph[$graph[$next].connections[$j].dest].distance -gt
               $graph[$next].distance + $graph[$next].connections[$j].weight)
            {
                $graph[$graph[$next].connections[$j].dest].distance =
                    $graph[$next].distance + $graph[$next].connections[$j].weight
            }
        }
        $graph[$next].isDead = $true
    }
    for([int] $i = 0; $i -lt $nodecount; $i++) {
        "The distance between nodes {0} and {1} is {2}" -f
            $source, $i, $graph[$i].distance
    }
}
$graph = @()
###
### Here’s where we define the different vertexi
### each vertex is a collection of edges
### an edge has a weight and a destination
$graph += vertex (edge -w 1 -d 2),(edge -w 2 -d 1) # 0
$graph += vertex (edge -w 3 -d 3),(edge -w 4 -d 4) # 1
$graph += vertex (edge -w 3 -d 4),(edge -w 5 -d 6),(edge -w 10 -d 7) # 2
$graph += vertex (edge -w 3 -d 5) # 3
$graph += vertex (edge -w 2 -d 5),(edge -w 3 -d 6) # 4
$graph += vertex (edge -w 2 -d 6),(edge -w 2 -d 7) # 5
$graph += vertex (edge -w 2 -d 7) # 6
$graph += vertex (edge -w 0 -d 0) # 7
Dijkstra $graph 0

### END SCRIPT

 Woo Hoo!

 

 

 

September 08

Getting Disk Usage Information

Some of you might know that I've spent a lot of time on UNIX systems.  One of the scripts that I used a bunch was /etc/dfspace.  If you don't know what dfspace is, it's a simple wrapper for df that provides disk usage info in a more human readable format than the output of df.  Since I really miss having that on Windows, I built it in powershell using the Get-WMIObject cmdlet.  Here's how it looks when you run it:

PS> dfspace
name                  Size (MB) free (MB) percent
----                  --------- --------- -------
C:                   152,499.84 76,827.33   50.38

By default, it only shows me the local hard drives.  By using the "-all" switch parameter I can get all the drives.

PS> dfspace -all
name                  Size (MB) free (MB) percent
----                  --------- --------- -------
A:                         0.00      0.00     NaN
C:                   152,499.84 76,826.80   50.38
D:                         0.00      0.00     NaN
Z:                    78,528.64  7,342.27    9.35

It can also get me the disk usage on another system via the -computer parameter (but you have to enable WMI remote access)

PS> dfspace -computer jimtrup2
name                 Size (MB) free (MB) percent
----                 --------- --------- -------
C:                   57,231.53 11,540.28   20.16

It gives me what I like, and it's actually a pretty simple script, where most of the script is creating the appropriate formatting

# Get-DiskUsage.ps1 (aliased to dfspace)
# Use Get-WMIObject to collect disk free info
# Can be used with remote systems
#
param ( [string]$computer = "." , [switch]$all)
# Formatting
$size = @{ l = "Size (MB)"; e = { $_.size/1mb};      f = "{0:N}"}
$free = @{ l = "free (MB)"; e = { $_.freespace/1mb}; f = "{0:N}"}
$perc = @{ l = "percent"; e = { 100.0 * ([double]$_.freespace/[double]$_.size)}; f="{0:f}" }
$name = @{ e = "name"; f = "{0,-20}" }
$fields = $name,$size,$free,$perc

# in case the user wants to see more than just local drives
$filter = "DriveType = '3'"
if ( $all ) { $filter = "" }

# go do the work by getting the information from the appropriate
# computer,
and send it to format-table with the appropriate
# fields and formatting info
get-wmiobject -class win32_logicaldisk -filter $filter -comp $computer |
    format-table $fields -auto

I suppose that I could handle division by zero better, but seeing NaN doesn't bother me.  If you don't like it, I'll leave that as an exercise for the reader :^)

August 30

Background "jobs" and PowerShell

One of the things that I'm used to on my unix systems is the ability to run applications in the background and that functionality is not available in PowerShell.  However, our RunSpace architecture can be used to create a pseudo-job environment.  A "simple" script, a few functions and a custom formatting file leaves me with a pretty good experience.  I'm not able to move jobs between foreground and background, but I never did that very much anyway.
 
So, the experience looks like this:
 
PS> new-job { get-date; start-sleep 5; get-date }
Job 0 Started
#<insert 5 second wait here>
PS>
Job 0 Completed
PS> jobs 0
JobId    Status       Command                      Results
-----    ------       -------                      -------
5        Completed    get-date; start-sleep 5; ... 8/30/2006 4:47:32 PM
PS> (jobs 0).results
Wednesday, August 30, 2006 4:47:32 PM
Wednesday, August 30, 2006 4:47:37 PM
 
This gives me what I need ok - I can run the command and get the results.  Let's do something a little more interesting (at least it is to me).  I want to find all the files on my system that are larger than 100mb and haven't been written for more than 3months.  This would probably take some time, since I'm going to be going over the entire filesystem.  Here's what I got:
 
PS> new-job { ls -rec c:\ | ?{ $_.length -gt 100mb -and $_.lastwritetime -lt [datetime]::now.adddays(-90) } }
Job 1 Started
I would like to see what's going on - so let's check:
 
PS> jobs
JobId    Status       Command                      Results
-----    ------       -------                      -------
0        Completed    get-date; start-sleep 5; ... 8/30/2006 4:56:25 PM
1        Running      ls -rec c:\ | ?{ $_.lengt...
 
after using the shell for a while, I get the following message (when I get a prompt):
 
Job 1 Completed
 
yea!  now I can check my results:
 
PS> jobs
JobId    Status       Command                      Results
-----    ------       -------                      -------
0        Completed    get-date; start-sleep 5; ... 8/30/2006 4:56:25 PM
1        Completed    ls -rec c:\ | ?{ $_.lengt... MSO060408_0001.wmv
PS> (jobs 1).results

    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Documents and Settings\jimtru\Desktop\mso

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/9/2006   2:15 PM  368465546 MSO060408_0001.wmv

    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Documents and Settings\jimtru\Desktop\mso\audio\051204 msoWav

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         12/5/2005  10:53 AM  121192364 2005-12-05 10_26.wav
-a---         12/5/2005  10:54 AM  213057644 2005-12-05 10_36.wav
 
So, I've got a bunch of huge wav files that I haven't touched for a while (they're recordings of the Microsoft Orchestra for those of you that are curious).   I can even stop the jobs if I want:
 
PS> new-job { ls -rec c:\ | ?{ $_.length -gt 100mb -and $_.lastwritetime -lt [da
tetime]::now.adddays(-90) } }
Job 2 Started
PS> (jobs 2)
JobId    Status       Command                      Results
-----    ------       -------                      -------
2        Running      ls -rec c:\ | ?{ $_.lengt...

PS> (jobs 2).stop()
Job 2 Stopped
PS> jobs
JobId    Status       Command                      Results
-----    ------       -------                      -------
0        Completed    get-date; start-sleep 5; ... 8/30/2006 4:56:25 PM
1        Completed    ls -rec c:\ | ?{ $_.lengt... MSO060408_0001.wmv
2        Stopped      ls -rec c:\ | ?{ $_.lengt... MSO060408_0001.wmv

 
The new-job script has all the magic in it, so here it is:
 
# New-Job.ps1
# This script creates an object that can be used to invoke a
# scriptblock asynchronously.
#
param ( [scriptblock]$scriptToRun )
##
## Object Created - Custom Object
##
## METHODS
##
## void InvokeAsync([string] $script, [array] $input = @()) 
## Invokes a script asynchronously.
## void Stop([bool] $async = $false) # Stop the pipeline.
##
## PROPERTIES
##
## [System.Management.Automation.Runspaces.LocalPipeline] LastPipeline     
##      The last pipeline that executed.
## [bool] IsRunning                                                        
##      Whether the last pipeline is still running.
## [System.Management.Automation.Runspaces.PipelineState] LastPipelineState
##      The state of the last pipeline to be created.
## [array] Results                                                         
##      The output of the last pipeline that was run.
## [array] LastError                                                       
##      The errors produced by the last pipeline run.
## [object] LastException                                                  
##      If the pipeline failed, the exception that caused it to fail.
##
## Private Fields
##
## [array] _lastOutput    # The objects output from the last pipeline run.
## [array] _lastError     # The errors output from the last pipeline run.
#region Message
$MultiplePipeline = "A pipeline was already running.   " +
    "Cannot invoke two pipelines concurrently."
##
## MAIN
##
# First check to be sure that there is a Job array
if ( test-path variable:jobs )
{
    if ( $global:jobs -isnot [array] )
    {
        throw '$jobs exists and is not an array'
    }
}
else
{
    $global:jobs = @()
}

# Create a runspace and open it
$config = [Management.Automation.Runspaces.RunspaceConfiguration]::Create()
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($config)
$runspace.Open()
# Create the object - we'll use this as the collector for the entire job.
$object = new-object System.Management.Automation.PsObject
# Add the object as a note on the runspace
$object | add-member Noteproperty Runspace $runspace
# Add a field for storing the last pipeline that was run.
$object | add-member Noteproperty LastPipeline $null
# Add an invoke method to the object that takes a script to invoke asynchronously.
$invokeAsyncBody = {
  if ($args.Count -lt 1)
  {
    throw 'Usage: $obj.InvokeAsync([string] $script, [Optional][params][array]$inputObjects)'
  }
  & {
    [string]$script, [array] $inputArray =  @($args[0])
    $PipelineRunning = [System.Management.Automation.Runspaces.PipelineState]::Running
    # Check that there isn't a currently executing pipeline.
    # Only one pipeline may run at a time.
    if ($this.LastPipeline -eq $null -or
        $this.LastPipeline.PipelineStateInfo.State -ne $PipelineRunning )
    {
      $this.LastPipeline = $this.Runspace.CreatePipeline($script)
      # if there's input, write it into the input pipeline.
      if ($inputArray.Count -gt 0)
      {
        $this.LastPipeline.Input.Write($inputArray, $true)
      }
      $this.LastPipeline.Input.Close()
      # Set the Results and LastError to null.
      $this.Results   = $null
      $this.LastError = $null
      # GO!
      $this.LastPipeline.InvokeAsync()
    }
    else
    {
      # A pipeline was running.  Report an error.
      throw
    }
  } $args
}
$object | add-member ScriptMethod InvokeAsync $invokeAsyncBody
# Adds a getter script property that lets you determine whether the runspace is still running.
$get_isRunning = {
  $PipelineRunning = [System.Management.Automation.Runspaces.PipelineState]::Running 
  return -not ($this.LastPipeline -eq $null -or
               $this.LastPipeline.PipelineStateInfo.State -ne $PipelineRunning  )
}
$object | add-member ScriptProperty IsRunning $get_isRunning
# Add a getter for finding out the state of the last pipeline.
$get_PipelineState = { return $this.LastPipeline.PipelineStateInfo.State }
$object | add-member ScriptProperty LastPipelineState $get_PipelineState
# Add a getter script property that lets you get the last output.
$get_lastOutput = {
  if ($this._lastOutput -eq $null -and -not $this.IsRunning)
  {
    $this._lastOutput = @($this.LastPipeline.Output.ReadToEnd())
  }
  return $this._lastOutput
}
$set_lastOutput = { $this._lastOutput = $_ }
$object | add-member ScriptProperty Results $get_lastOutput $set_lastOutput
$object | add-member Noteproperty _lastOutput $null
# Add a getter for finding out the last exception thrown if any.
$get_lastException = {
  if ($this.LastPipelineState -eq "Failed" -and -not $this.IsRunning)
  {
    return $this.LastPipeline.PipelineStateInfo.Reason
  }
}
$object | add-member ScriptProperty LastException $get_lastException
# Add a getter script property that lets you get the last errors.
$get_lastError = {
  if ($this._lastError -eq $null -and -not $this.IsRunning)
  {
    $this._lastError = @($this.LastPipeline.Error.ReadToEnd())
  }
  return $this._lastError
}
$set_lastError = { $this._lastError = $args[0] }
$object | add-member ScriptProperty LastError $get_lastError $set_lastError
$object | add-member Noteproperty _lastError $null
# Add a script method for stopping the execution of the pipeline.
$stopScript = {
  if ($args.Count -gt 1)
  {
    throw 'Too many arguments.  Usage: $object.Stop([optional] [bool] $async'
  }
  if ($args.Count -eq 1 -and [bool] $args[0])
  {
    $this.LastPipeline.StopAsync()
  }
  else
  {
    $this.LastPipeline.Stop()
  }
}
$object | add-member ScriptMethod Stop $stopScript
# finally, attach the script to run to the object
$object | add-member Noteproperty Command $scriptToRun 
# Ensure that the object has a "type" for which we can build a
# formatting file.
$object.Psobject.typenames[0] = "PowerShellJobObject"
$object.InvokeAsync($scriptToRun)
#$object
$object | add-member NoteProperty JobId $jobs.count
"Job " + $jobs.count + " Started"
# Since we add this job to the we need to be sure that
# we can remove jobs.  The clear-job function will allow for that
$global:jobs += $object

 
I've created 2 functions to help me with getting the job information (and an alias to make it a bit more UNIX like) add these to your profile.
 
# get my job
function get-job
([int[]]$range = 0..($jobs.count-1))
{
    $jobs[$range]
}
# make a UNIX like alias
alias jobs get-job
function clear-job
{
    # remove all the variables that hold my job info
    rm variable:jobs
    rm variable:jobshash
    # call the garbage collector, just because I can
    [system.gc]::Collect()
}
 
Then to be sure that I know when a job is finished, I added this to my prompt function:
 
    ### Job info code - only useful for new-job script
    ### paranoia - make a jobhash hashtable so I can track what jobs are done
    if ( $jobshash -isnot [hashtable] ) { $global:jobshash = @{} }
    $global:jobs | where { $_.lastpipelinestate -ne "Running" } | foreach-object {
        if ( ! $global:jobshash[([string]$_.jobid)] )
        {         
            $global:jobshash[([string]$_.jobid)] = 1
            if ( $_ ) { write-host Job $_.jobid   $_.lastpipelinestate }
        }
    }
    ### End job info code
 
Finally, I created a format table view so I can see the output the way I want (when I get a PowerShellJobObject - see the new-job script).  My profile runs
    update-formatdata c:\powershell\format\job.format.ps1xml
to ensure that the format file get loaded.  Here's the content of the format file
 
PS> get-content c:\powershell\format\job.format.ps1xml
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
    <ViewDefinitions>
        <View>
            <Name>PowerShellJobObject</Name>
            <ViewSelectedBy>
                <TypeName>PowerShellJobObject</TypeName>
            </ViewSelectedBy>
            <TableControl>
                <TableHeaders>
                    <TableColumnHeader>
                        <Label>JobId</Label>
                        <Width>8</Width>
                    </TableColumnHeader>
                    <TableColumnHeader>
                        <Label>Status</Label>
                        <Width>12</Width>
                    </TableColumnHeader>
                    <TableColumnHeader>
                        <Label>Command</Label>
                    </TableColumnHeader>
                    <TableColumnHeader>
                        <Label>Results</Label>
                    </TableColumnHeader>
                </TableHeaders>
                <TableRowEntries>
                    <TableRowEntry>
                        <TableColumnItems>
                            <TableColumnItem>
                                <PropertyName>JobId</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>
                                <PropertyName>LastPipelineState</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>
                                <PropertyName>Command</PropertyName>
                            </TableColumnItem>
                            <TableColumnItem>
                                <ScriptBlock>
                                    if ( $_.results -is [array])
                                    {
                                        $_.results[0]
                                    }
                                    else
                                    {
                                        $_.results
                                    }
                                </ScriptBlock>
                            </TableColumnItem>
                        </TableColumnItems>
                    </TableRowEntry>
                </TableRowEntries>
            </TableControl>
        </View>
    </ViewDefinitions>
</Configuration>
 
The extra functions and addition to my prompt and the formatting file are all extra's and not really necessary to the operation of the runspace.  It just makes it easier for me to deal with.
 
There you have it - you can run background "jobs" too!  Right now, I use a simple array to hold all my jobs - in the future I'll use an array list, so that way I can remove the old jobs if I want (rather than just blowing away the entire array as clear-job does.
 
jim
 
 
May 14

PowerShell and file version information

I often want to get the version information about the files on my system.  Version information is provided as part of the System.Diagnostics.Process object, but I often want the version information about applications that aren't running.  This script allows me to get that information.  I've written the script so it handles both piped input and command line arguments.  It uses the begin/process/end features of the scripting language, so I can get it to behave almost like a compiled cmdlet. 
 
Here's what it looks like when I use it:
PS> ls c:\windows\*.exe | get-fileversion

ProductVersion   FileVersion      FileName
--------------   -----------      --------
1.6.0.2          1.6.0.2          C:\windows\Alcmtr.exe
1.1.0.27         1.1.0.27         C:\windows\alcwzrd.exe
6.00.2900.2180   6.00.2900.218... C:\windows\explorer.exe
5.2.3790.2453    5.2.3790.2453... C:\windows\hh.exe
5, 51            5, 51, 138, 0    C:\windows\IsUninst.exe
1.1.0.8          1.1.0.8          C:\windows\MicCal.exe
5.1.2600.2180    5.1.2600.2180... C:\windows\NOTEPAD.EXE
5.1.2600.2180    5.1.2600.2180... C:\windows\regedit.exe
2.0.1.7          2.0.1.7          C:\windows\RTHDCPL.exe
1.0.1.51         1.0.1.51         C:\windows\RTLCPL.exe
2, 5, 0, 5       2, 5, 0, 5       C:\windows\RtlUpd.exe
1, 0, 0, 21      1, 0, 0, 21      C:\windows\SoundMan.exe
5.1.2600.0       5.1.2600.0 (x... C:\windows\TASKMAN.EXE
1,7,0,0          1,7,0,0          C:\windows\twunk_16.exe
1,7,1,0          1,7,1,0          C:\windows\twunk_32.exe
3.10.425         3.10.425         C:\windows\winhelp.exe
5.1.2600.2180    5.1.2600.2180... C:\windows\winhlp32.exe
or
PS> get-fileversion C:\monad\rc1\System.Management.Automation.dll

ProductVersion   FileVersion      FileName
--------------   -----------      --------
1.0.9567.1       1.0.9567.1       C:\monad\rc1\System.Management.Automation.dll
Here's the script - it's pretty straight forward. Since I don't know whether I'm going to have piped input or not, I use the begin script block to declare a couple of functions that will be used by either of the process or end blocks.
The real work is done in the function GetVersionInfo where I simply call the GetVersionInfo static method on the System.Diagnostics.FileVersionInfo type. Note that most of the code is error correction and ensuring that I get a proper path when I call the GetVersionInfo method.
param ( [string[]]$paths )
begin {
    # I want to do some stuff with relative paths.   
    # create a variable that I can use later
    $P = [string](get-location)

    # the workhorse of the script
    function GetVersionInfo
    {
        param ( [string]$path )
        # resolve the path, we're going to need a fully qualified path to hand
        # to the method, so go get it.  I may not have that depending on how
        # was called
        $rpath = resolve-path $path 2>$null
        # the thing we hand to the method is the path string,