James O'Neill's blog

Windows Platform, Virtualization and PowerShell with a little Photography for good measure.
Posts
  • James O'Neill's blog

    A little more on PowerShell

    • 6 Comments

    I've been showing PowerShell on the roadshow, and Steve warning me about it becoming the "Look-how-clever-I-am-with-PowerShell show". Actually, I quite like the idea of a "Look-how-clever-PowerShell-makes-you show". Working on some of bits and pieces of PowerShell for managing hyper I've found a couple of new corners which I thought I'd share.

    I wanted to show the tree of snapshots taken of a Hyper-v Virtual Machine ... and let the user choose one of them.  I ended up with a semi-generic "Choose-Tree" function, and that sent me back to the choose functions I've written about before. I wanted to have something totally generic like this

       choose-list (Get-WmiObject win32_diskdrive) @("DeviceID", "Model")
    
    

    ID DeviceID           Model
    -- --------           -----
    0 \\.\PHYSICALDRIVE0 Hitachi HTS721010G9SA00 ATA Device
    1 \\.\PHYSICALDRIVE1 Generic USB Card Reader USB Device
    2 \\.\PHYSICALDRIVE2 Multi Flash Reader USB Device

    Which one ?:

    The idea is simple enough, pass the function an array of data and other array of the field names I want displayed, put a counter alongside them and let the user enter the index into the array for the item they want.

    This led me to using variables and parameters in places I haven't done before One was using a variable to hold a field name. Like this

       $foo="TotalPhysicalMemory"
       (Get-WmiObject win32_computersystem).$foo

    Very useful if I need to pass a parameter to a function to tell it which property to use from the objects it was passed. Building a tree for example, which field is displayed, which gives a node's parent, and so on. Then I started looking at using an array of strings to hold the field names, like this

       $foo=@("TotalPhysicalMemory","Model")
    Get-WmiObject win32_computersystem | format-table -property $foo

    That works very nicely too. Because Powershell lets us mix types of item in an array we can put in hash tables which store custom fields. So a design formed... Pass data and Fields as parameters, add the counter custom-field that I was already using in my choose functions to the Fields array (put it an array and join it with the array of fields passed to the function), and use that in a format-table command. Since some of Choose functions had multiple selections and some single I had a "Multiple" parameter and that changes the prompt / selection at the end. So my generic choose-from a-list function ends up as half a dozen lines.

       function choose-List
       {Param ($Data , $fieldList , [Switch]$Multiple)
        $global:Counter=-1
        $fieldlist=@(@{Label="ID"; expression={ ($global:Counter++) }}) + $fieldList
        $data | format-table -autosize -property $fieldList | out-host
        if ($Multiple) { $Data[ [int[]](Read-Host "Which one(s) ?").Split(",")] }
        else           { $Data[        (Read-Host "Which one ?")           ] }
       }

    Each "choose" function - choose VM, Choose network etc then becomes one line.

    Technorati Tags: ,
  • James O'Neill's blog

    Hyper-v and Snapshots (Part 1)

    • 5 Comments

    We often talk about "rolling back" to a snapshot, but here, some of the snapshots we can apply aren't simply forward or backward, hence Hyper-V talks about applying snapshots.

    It also talks about Deleting snapshots which causes some confusion. Deleting a snapshot means foregoing the ability to return to that point - we can't apply a deleted snapshot, that's obvious enough. The saved memory state (if there is one) is deleted but what about the data in the AVHD file ? If a Snapshot has children we can either delete the whole subtree, or we can delete just the parent snapshot. Internally Hyper-v works out when it can merge and/or delete AVHD files - a process which can take some time (you can tell if this operation is pending because the edit button for the hard disk in the machine's settings is grey'd out). 

    Here's an example The machine is running quite happily and has never been snapped. Late on Monday make a snapshot. This does two thingsHyper-V-Snapshots

    1.If the Machine is running or in a saved state we make a copy of memory

    2. We stop writing changes to its VHD and start writing changes to a new AVHD file. (Lets call this AVHD-1)

    At any point when we want to revert, we go back to the original hard disk and the Monday memory state. Throughout Tuesday changes are written to the AVHD-1then on Tuesday night we do another Snapshot. The same thing happens

    1.If the Machine is running or in a saved state we make a copy of memory

    2. We stop writing changes to AVHD-1 file and start writing changes to a new AVHD file. (Lets call this one AVHD-2)

    Now we can revert to two points, Monday's memory state and the original VHD or Tuesdays memory state and the combination of the original VHD and AVHD-1

    Lets assume that on Wednesday something happens to cause us to go back to Monday's state. We can either (a) Keep AVHD-2 and save the memory state as it was on Wednesday or (b) Discard AVHD-2 and memory state. Either way the server now starts a new AVHD file - lets call this one AVHD3. Thursdays changes get written to this, and on Thursday night as before we do another snapshot and start AVHD4 for Friday's changes and keep the memory state as it was on Thursday.

    Now we can apply 3 states (or 4 if we kept Wednesday's).

    Now for the obligatory bit of powershell, because of course this is scriptable.

       Function New-VmSnapshot  
    {Param( $vm=$(Throw "You must specify a VM") )
    if ($vm -is [string]) {$vm=(Get-VM $vm) }

    $arguments=($vm,$Null,$null) $result=$VSMgtSvc.psbase.invokeMethod("CreateVirtualSystemSnapshot",$arguments) if ($result -eq 4096) { $arguments[2] }  else  {"Error, code:" + $result}
    }

    [Update. A bit of PowerShell 2.0 crept into the above. In 1.0 you can't call the .InvokeMethod  method of a WMI object directly, you have to call it via .psbase]

    In an earlier post I described Get-VM and explained that I set up a variable

       $vsMgtSvc = Get-wmiObject -nameSpace root\virtualization -class Msvm_virtualSystemManagementService

    All the work here is done by the CreateVirtualSystemSnapshot method, and we pass it the Machine and 2 nulls. Normally it will return 4096 - the code for "started processing in the background" and the second Null magically contains the job ID so the function returns that. So you can invoke the function as $JobId=(New-VmSnapshot  $Tenby) and make tracking the job afterwards that bit easier. There are two more methods which we can call, RemoveVirtualSystemSnapshot, and ApplyVirtualSystemSnapshot oddly the latter only requires the machine and the snapshot reference, even though the snapshot says which machine it came from but trying to apply a snapshot to a new, clean VM fails. Maybe it's something that's under consideration for a future version. I'll describe these two in my next post.

     

    [Update somehow the order of the paragraphs got scrambled, they're back in the right order now]

  • James O'Neill's blog

    Hyper-v Snapshots part 2.

    • 4 Comments

    In my last post I explained how snapshots work and gave a little bit of PowerShell for creating a one . In the post before that I talked about creating a generic  choose-tree function. What I wanted was to be able to call Choose-tree  List_Of_Items First_Item  PathPropertyName, ParentPropertyName, PropertytoDisplay and get a tree view I can choose from: like this

        $folders=dir -recurse | where-object {$_ -is [system.io.directoryInfo]}
        choose-tree $folders (get-Item (get-location) ) "PSPath" "PsParentPath" "Name"
    
    

    0    +windowsPowershell
    1    | |--Nivot
    2    | |--Pics Which one ?: 2

    The key thing in this is that PowerShell lets us use variables/parameters to hold field names. The logic is pretty simple. Take an array of items, and tell the function which one to start at, Output that item, if it has any Children call the function recursively for each of them. Checking for children is where this ability to pass property names is important, because I can use  where-object {$_.$parent -eq $startat.$path.ToString()} to say "where the field I said holds the parent, matches the field I said holds the path" I put a "ToString" on the end because I found it doesn't like being passed "path.path" and that's needed for some WMI items; toString() returns the path in this case but it's safe for strings too. When the function calls itself it specifies how many levels deep in the tree the current item is - each level of recursion adds 1 to $indent in the function.

    I wrote an "Out tree" before doing "choose-tree", most of the code below is associated with making choices When processing the topmost item it sets up a counter to allow the user to choose the items, and because the output order might not be the same as the input order it also sets up an array to hold ordered items. Once all the child items have been processed it prompts the user for a selection  and returns the item at that position in the array. 

    The only thing that I've done here that is out of the ordinary for me is I don't like using the -f operator on strings because it makes for unreadable code. "{0, -4}" -f $counter. Says "Put argument at position 0 into this string , right justified to 4 characters", which is just what I need, and I've put in the rest of the output line into the same construction.

       Function Choose-Tree
       {Param ($items, $startAt, $path=("Path"), $parent=("Parent"), 
        $label=("Label"), $indent=0, [Switch]$multiple)
        if ($Indent -eq 0)  {$Global:treeCounter = -1 ;  $Global:treeList=@() } 
    $Global:treeCounter++
    $Global:treeList=$global:treeList + @($startAt)
    $children = $items | where-object {$_.$parent -eq $startat.$path.ToString()} if   ($children -ne $null)
    { $leader = "| " * ($indent)
    "{0,-4} {1}+{2} "-f  $Global:treeCounter, $leader , $startAt.$label | Out-Host
    $children | sort-object $label |
    ForEach-Object {Choose-Tree -Items $items -StartAt $_ -Path $path `
                          -parent $parent -label $label -indent ($indent+1)}
         } else { $leader = "| " * ($indent-1)        
    "{0,-4} {1}|--{2} "-f  $global:Treecounter, $leader , $startAt.$Label  | out-Host } if ($Indent -eq 0) {if ($multiple) { $Global:treeList[ [int[]](Read-Host "Which one(s) ?").Split(",")] }
    else           {($Global:treeList[ (Read-Host "Which one ?")]) } 
                          } }

    And so to snapshots. 

    The parent partition and every child MsVM_ComputerSystem WMI object which represents it. The "Name" field in this object is actually a GUID. There is a second object MsVM_VirtualSystemSettingData: each VM, and each of its snapshots has one of these objects. The Settings data object for VM itself has it's GUID in both the InstanceID and systemName fields, but the Snapshots have their own instanceID with the VMs GUID in the system name field. As with most of my functions I things up so I can pass the MsVM_ComputerSystem object or pass a string and use Get-VM  to convert it. Then I it's one Get-WMObject operation to get the Snapshots.

       Function Get-VMSnapshot
       {Param( $VM=$(Throw "You must specify a VM") )
    
    if ($VM -is [String]) {$VM=(Get-VM -machineName $VM) }
    Get-WmiObject -NameSpace root\virtualization -Query "Select * From MsVM_VirtualSystemSettingData Where systemName='$($VM.name)' and instanceID <> 'Microsoft:$($VM.name)' " }

    Time to combine choose-tree and get-snapshot to choose my snapshots from a tree. As I said above , the Name field is actually a GUID, and the display name for the Snapshot is in the elementName . So I display the tree of choices,starting with the "Root" snapshot. [Note I'm aware that I don't cope with the situation where you delete a root snapshot with two children and get two roots]

       Function Choose-VMSnapshot
       {Param ($VM=$(Throw "You must specify a VM"))
        $snapshots=(Get-VMSnapshot $VM )
        Choose-Tree -items $snapshots -startAt ($snapshots | where{$_.parent -eq $null}) `
            -path "Path" -Parent "Parent" -label "elementname" }

    Now I can choose my snapshots, it's easy to tell a function like Remove-snapshot or apply-snapshot what I want. Here's Remove-Snapshot , which I can call with something like
    Remove-snapshot -snapshot (choose-Snapshot Core). Pretty simple stuff, I use the variable pointing to to the virtual System Management Service, as I did when creating a new snapshot this time I just need to invoke the RemoveVirtualSystemSnapshot method. As with the new snapshot it should return 4096 for "started processing in the background" , and I return the Job ID.

       Function Remove-VMSnapshot 
       {Param( $snapshot=$(Throw "You must specify a snapshot") ) 
        $arguments=($snapshot,$Null) 
        $result=$VSMgtSvc.psbase.InvokeMethod("RemoveVirtualSystemSnapshot",$arguments) 
        if ($result -eq 4096){ $arguments[1] } 
        else                  {"Error, code:" + $result} 
       }

    Finally I might want to apply a snapshot , and this needs us to specify the VM and snapshot. I've written this so that if the Snapshot is omitted the user is prompted to select it. It's the same process again, except this time we use the ApplyVirtualSystemSnapshot Method

       Function Apply-VMSnapshot
       {Param( $VM=$(Throw "You must specify a VM"), $SnapShot=(choose-VMsnapshot $VM))
        if ($VM -is [String]) {$VM=(Get-VM -machineName $VM) }
        $arguments=@($VM,$snapshot,$null)
        $result=$VSMgtSvc.psbase.InvokeMethod("ApplyVirtualSystemSnapshot", $arguments)   
    if ($result -eq 0) {"Success"} elseif ($result -eq 4096) {"Job Started" | out-host $arguments[2]} else {"failed"} }

    [Update. There were a couple of bits of PowerShell 2.0 in the above. In 1.0 you can't call the .InvokeMethod  method of a WMI object directly, you have to call it via .psbase]

    If you're wondering what to with the Virtual Hard disks I showed I'll get round to that soon.

  • James O'Neill's blog

    Something for the photographers: Silverlight Deep-zoom formerly "Sea-Dragon"

    • 4 Comments

    With all the other stuff I've been doing lately I'm champing at the bit to get out and take some more photos. Still here I am slaving over a hot laptop.

    Search suggests haven't mentioned Sea-Dragon before - but I've talked about Photosynth, which is one of the technologies that use it. We've been saying since at least last October that Sea-Dragon is going into Silverlight.  Which is exciting stuff, it's also getting a new name "Deep zoom".  Eileen picked up some stuff on this - we have Deep Zoom Composer available for Download. I've had a brief play with it but it's output is really intended to go into something else*; more interesting - to me at least is Photo Zoom. Imagine a "contact sheet" view of your photos with pretty much unlimited zoom in and out. That, in a nutshell is Photozoom. As yet it is not a fully featured photo gallery - it doesn't have the tags and other text that I'd want but as a proof of concept of where this is heading it's exciting stuff.

    We always have bit "in the works" that I can't really talk about, but an interesting bit of software came my way this week, and the folks behind it have said I can talk about what it produces. What they've given some of us is a test harness for both ideas, and code to implement them. In what form these see the light of day outside the company and when - if at all - remains to be seen.

    So here is one of my favourite pictures, party because I sold it a print of it to someone whose London Office is in there

    st pauls Click for the Deep zoom version

    The original was 38 Mega-Pixel image and the print was 150x21 CM in size (60" x 8" ) an 8:1 aspect ratio is lousy to view on screen and even worse if you want to store it online.
    But now I have a version set up for deep zoom. - I can find the window of my patron's office, but I can move around it interactively much like looking at a big print hanging on the wall.

    Before you click through (a) It needs Silverlight 2 Beta installed. If you get an error about Invalid XML character after installing Silverlight you need to close and restart the browser. (b) The experience is OK with the glidepoint device on my laptop, but it's much better with a wheel mouse.

    *Update. My colleague Marc Holmes gave me some info, which is now on his blog, to show me how to upload my frist DeepZoomComposer project to silverlight. You can see it here nothing too fancy, just a few pictures that I happen to like. in one project.

  • James O'Neill's blog

    On knowing your sh*t

    • 4 Comments

    It's been an interesting few days, Monday was the Glasgow road-show event and Thursday was our day in Newcastle. The team didn't look upon flying with any great enthusiasm. So rather than returning home, drawing breath and heading North again we decided to stop en-route for an extra day and night: since we'd missed off-site event that the rest of our group had to spend time doing team stuff and thinking about goals for the financial year that starts on July 1st, we used the time for that - while enjoying some of the best countryside the UK has to offer. It was time well spent and  - thinking as a shareholder - I was glad to see a reasonable chunk of money saved (not quite so glad that a quirk of our expense policy means I'm paying a little of the cost myself) 

    And so to Newcastle; we've visited Newcastle twice and got a good reception both times so it's a place I'm glad to come back to. (Some audiences seem pleased  that we bother going to them at all. London audiences expect us to go there and are the hardest to please.) Instead of being Travel weary, we were in a good frame of mind and delivered the best event we've done on this trip. Last time we were in Newcastle  Jonathan Noble met us and we ended up entering a pub quiz (and got close to winning!), so we gave him the task of finding another one and were joined by half dozen more "community" people. The quiz was fun and we might have won it, but we came in a contented third. There was an end-of-evening Jackpot prize for a one-off question: 25p to buy a slip, a £100 prize and one question asked after the slips were sold. The question. What are coprolites ?

    Some years back a friend of mine - another of the Davids - bought the board game of Who wants to be a Millionaire ? Being on a few people's phone-a-friend list I did fairly well and found myself at the "£1,000,000" question. It was "What date was the battle of Hastings" - everyone assumes 1066, but not what year, but what day-of-the-year.  I'd once sent my Dad a birthday card which said on the outside "Do you know what day it is ?" and on the inside I'd written "The 925th anniversary of the battle of Hastings ? ", because he (and Mrs Thatcher if I remember correctly) both have the day of the battle as their birthday. So when the answers were  "13th of August" , "13th of September", "13th of October", or "13th of November" it was too easy. While we're on battles and anniversaries a different David celebrates wedding anniversary on Trafalgar day. I don't know how this stuff sticks in my head, but it's a useful trait for a technical chap.

    I don't know why I know about Coprolites. But I do know they're fossilized dinosaur droppings. Whether to para-phrase something from the film broken arrow I don't know if I was more surprised that dinosaur poo CAN be fossilized, or that it is common enough that we have a word for it it . So £100 came my way. One Geordie - a good 20 years my senior - asked me with a huge grin on his face if "that means you know a lot about old sh*te" quite a few Microsofties would say that was a fair description.  I told my daughter about football that "you win as a team or lose as a team" and I didn't think of the prize as my money.  The winning team in the main quiz  put their prize in the Pub's charity boxes (RNLI and RNIB) and when I suggested that we do the same, all of my team agreed. It might be the first time our charity matching scheme has been presented with a pub receipt to support a claim - all being well the two charities should get £50 each; and that still doesn't wipe out the money we saved.

  • James O'Neill's blog

    The joy of feedback [again]

    • 4 Comments

    I make a point of saying at the roadshows that we read all the comments and take note of them I wanted to share one particular comment but first off I want to give you a flavour of what people said they liked at one of last weeks events; here they are, as posted.

    • Good demonstrations.
    • Venue! much better than the last Technet I went to
    • Cinema venue was comfortable and presentations were easy to see.
    • As usual, very well presented and informative. Good venue.
    • Clarity of speakers and how excellent delivery. Great hospitality and lunch!
    • The demos - done very well by real techies with good communication skills - thank you.
    • The humour and real stories.
    • Feature demos and examples.
    • The location was surprisingly effective. The guys really knew their stuff.
    • Very clear presentations with well timed breaks
    • Presentations were excellent, very informative and entertaining. All the speakers communicated well and kept the presentation flowing. The presenter shared good banter.
    • The style of presentation from the presenters. Very informative and enjoyable.
    • Event was well presented, and at a resonable pace.
    • Reasonable venue, good investment in food/drinks to keep people on board, not too advertorial/ sellsellsell, some free stuff, reasonable level of knowledge by the team, good parking and easy (ish) to get to, I had a 200 mile round trip. We could hear the presenters and see the screen which is always a good start.
    • The friendly but professional presetation of the event.
    • Hands on demos and labs sessions. coffee and cake in the morning was much needed and very good. Presenters we're also excellent and really worded as a team. The software trials were also extremely generous.
    • I also liked the presentations and speakers, while done very professionally it wasn't deathly serious.
    • Professional and yet informal putting people at easy.
    • Easy going , informative and entertaining.

    We know that everyone doesn't always feel the same, and we had one person who must have got close the space limit with the following comment in the what could we do better section. It's worth reading just for the penultimate sentence which I've put in bold.

    Presentation skills were somewhat lacking, no co-ordination of presentations/presenters, the projector was WAY out of focus and left me with a headache, what were your technical staff doing during the sessions? They were not wtaching and helping you out with mic/tech issues thats for sure so get new ones. The presenters jokes were so bad they could be on "The IT Crowd" (this is not a complement btw), bin the hats we couldn't see your eyes and this means nobody trusts you plus they just looked daft, when asking for a poll to prove a point be sure it's going to go your way as several didn't which was embarassing, public transport links were non existant, the American guy may not want to bother with Environmental issues like power saving but it's my organisations 4th most important issue (our electricity bill is circa 1.4Million UKP/year) send him back to his oil rich Texas ranch please or get with the program, how come the only females on the team were Georgina (relegated to admin functions) and some leggy microphone holders? Can we please have some diversity in your team of techno boffins. Along the same lines I could see 2 of the presenters trying very hard to keep their "don't suffer fools/women/managers/boss/customers gladly" attitude under control, trying and only just succeeding. Please educate your presentation team that "in jokes" should not be done whilst on stage, they may make you laugh but they make the audience wince and think your unprofessional. Bin the hats. Use a video mixer instead of a kvm switch and for goddness sake have a corp. screen to drop back to if your still fidling with powerpoint because we don't want to see it. Get better compressed video's for your presentations and better specced machines to play them on. Music: was it supposed to sound like a tinny 80's set of headphones? I think the sound engineer was taking the piss, get a new one. It was difficult to kick off conversations with other delegates, maybe a larger area between sessions/larger name/company fonts on the badge and most importantly some facilitators in the audience/foyer to get people talking. Some parts of the presentations were slightly too geeky and this was more pronounced when things did not go to plan. Once things went out of kilter it just looked tragic, sorry. Don't get me wrong though, I did enjoy the day and I will come to some more as/when they are advertised. I was expecting something a bit slicker but at the end of the day it could have been a whole lot worse.

     

    As for the lack of women presenting, Eileen opted not to present on this tour, and we don't have any other women on the team. I understand that when I was hired no woman applied, I know because I interviewed all the candidates for Viral's and Andrew's roles that no woman applied for either of those either. That's why Eileen spends time trying to get women into technology. I don't know why the company that stage the events for us have women as "meeters and greeters" , although the women in question might be a little surprised to be called "leggy". As for 2 of the presenters trying to keep their "don't suffer women gladly" attitudes under control unless this was a reference to Steve pulling Viral up on his use of "Guys" to mean "people" instead of "men" - think of "Friends", where everyone calls everyone "you guys" regardless of gender.

  • James O'Neill's blog

    Ways to tidy up my PowerShell - including making a hash of stuff

    • 3 Comments

    Please excuse the bad pun... When I first wrote the function I posted to display the state of virtual machines, I used a construction which has been familiar to programmers since time immemorial.

      If X=1 output this

    If X=2 output that

    etc

    Most modern programming languages, including PowerShell, have some kind of switch construction which is a little tidier but they're still bulky...
    I had put constants for each of the states in the .PS1 file which holds all my PowerShell VM functions. But this was more as a way of having a note of them than something I was going to use in my code. I could have written the Start-vm function (in the same post) like this 

       $VM.RequestStateChange($Running)

    and re-coded my display function as

       switch ($_.EnabledState) { $Running {"Running"}
    $Stopped {"Stopped"}
                             $Paused {"Paused"}
    etc

    but it still needs a line for each state. For completely separate reasons I was looking at hash tables. It takes one line to create a hash-table of return codes:

        $VMState=@{"Running"=2 ; "Stopped"=3 ; "Paused"=32768 ; "Suspended"=32769 ; 
    "Starting"=32770 ; "Snapshotting"=32771 ; "Saving"=32773  ; "Stopping"=32774 }

    So I changed the way I start and stop machines: one function does the work: expanding arrays, converting strings to computerSystem objects and actually changing the state: like this

       Function Set-VMState 
       {Param ($VM , $state)
        if ($VM -is [Array]) {$VM | ForEach-Object {Set-VMState -VM $_ -State $state} }
        if ($VM -is [String]) {$VM=(Get-VM -Machinename $VM) }
        if ($VM -is [System.Management.ManagementObject]) {$VM.RequestStateChange($State) } 
    $VM = $null }

    Using the hash Table and then I have Start, Stop and Pause functions like this:

       Filter Start-VM
       {Param ($VM)
    $if ($vm -eq $null) ($vm=$_} Set-VMState -VM $VM -State $vmStates.running
    $VM = $Null }

    I also made a change to accept input from the pipe e.g. Get-VM "James%" | start-VM , there are two changes (a) use a FILTER instead of a FUNCTION and (b) pick up the piped input in $_ . So I've got quite a few functions where I should  change this.
    [Update, I'm not sure if this is the approved way of Piping, but I quickly learned that I should add the $VM=$Null at the end, other wise when 5 items  are piped in function is run 5 times, using the first one each time.]

    HashTables are a one-way lookup: $VMstates.running returns the value with a key of "Running" - 2 in the Start-VM filter.  If I have "2" and want to get back to "Running" there isn't a built in way(that I know of). However PowerShell has a GetEnumerator which dumps out the whole hash table as Key/value pairs, which that makes it easy to get the name we want.

       function Convert-VMStateID
        {Param ($ID)   
    ($vmState.GetEnumerator() | where {$_.value -eq $ID}).name }

    and using the choose-list function I showed before before , choose-VM becomes a one liner

    Function Choose-VM
    
    {choose-list -data (Get-VM) -fieldList @(@{Label="VM Name"; Expression={$_.ElementName}},
    @{Label="State"; Expression={Convert-VMStateID -ID $_.EnabledState}}) }

    (In principle it is a one liner ... in  practice I'm going to have a -multi switch to allow single or multiple selections.

    One other thing I've done in this tidying up exercise is to make sure I name my parameters in scripts. This means I really should go back to my Choose-list function and rename the "Field list" parameter to "Property" to match Powershell's built-in cmdlets (just as I have been trying to use existing Verbs and write my nouns in the singular !).  Identifying parameters by position doesn't make for readable code:  the following two lines are equivalent, but which would you rather see in a script (not the one you'd rather type at the command line !)

    Set-VMState -VM $VM -State $vmStates.running  
    Set-VMState  $VM  $vmStates.running 

     

  • James O'Neill's blog

    Top travel tip. Use the calendar. Properly

    • 3 Comments

    One of the things that we noticed on the roadshow was the *much* better system for getting us feedback (see here and here oh and here ) and - always looking for ways to improve our processes - a couple of us noted that there's a big document mailed out with the event information for the presenters, but when we pull out our phones the calendar appointment doesn't have the location of the event in it. Each of the presenters has to copy the information out of the document and paste it into the calendar. None does. We try not to print stuff which we can see on a laptop, and we don't want to get a laptop out to program the sat-nav. So next time hopefully we'll get two appointments, one with the Hotel and it's address, and one with the venue and it's address.

    Putting data in the Calendar has two advantages. (1) It's sync'd and always with me (2) Everyone has read access to my Calendar. So anyone can find where I am in an Emergency.

    In July I'm off to Seattle and I booked my flights on Friday, a year ago I wrote about the stupidity of our Travel booking process and things haven't got any better. Our Travel agent send the itinerary as a copy-protected PDF. Why on earth they can't send me flight details in ICS / VCS format beats me. So the process is print PDF to XPS, Open XPS, select, copy , paste, reformat.

    Clearing out my Inbox I came to the mail marked "Save the date". Now when I meet the person who sent this I'm going to give them the verbal equivalent of a gentle Slap. For 10 years Microsoft has used outlook. For 5 years before that we had 5 years of Schedule+, I can only assume he's new and doesn't know that to save a date you send a calendar request. The sender compounds the offence by putting the date and venue details in as a bitmap - not text - so its not sync'd to a phone and not read by Outlook Voice Access. So 350 people have to take a couple of minutes each typing all their own calendar requests: that adds up to a working day wasted. Or maybe they won't bother and will be wandering round Seattle looking lost.

    In all 3 cases I'm left asking - why am I the one doing this ?

  • James O'Neill's blog

    "Lady licensing" blog.

    • 3 Comments

    George has been telling everyone recently about Emma Healy's blog on Licensing. I don't often plug other blogs, but I think this one is worth your attention

    • Before I came to Microsoft I used to wonder "Why can't they make licensing simpler"... these days I have some idea why.
    • Technical people tend to look on licensing matters as "paperwork" with all the disdain that implies, and never take the time to find out about it.
    • Licensing people don't tend to be visible in public

    I wouldn't pretend that I would go and read about licensing every single day, but that's the joy of RSS, you can sign up and every so often something that you value comes by. This one on Virtualization for example.

    However is it just my puerile mind which makes the title that Emma has picked on Live Spaces - Lady Licensing - sound like something else.

  • James O'Neill's blog

    Off topic. The Cost of fuel, market forces and being green

    • 3 Comments

    Part of my salary package working at Microsoft UK is a company car, for which Microsoft buys the fuel. I can opt out of this scheme and take money instead (which is taxed like any other Salary payment) and the Tax office also works out the notional value of the car and fuel (both are based on the C02 emissions of the car)- the critical thing is that this doesn't change with the amount of fuel I use, or the price of fuel. In effect the cost of fuel to me is fixed however many miles I do; which gives me a financial incentive to use the car rather than greener forms of transport. It also takes away any financial incentive I have to work from home and when I do it is based on productivity and work/life balance (if anything is going to hinder my getting the job done, better that it's my son asking what I'm doing on the computer than the hubbub in our hotdesk pens)

    Last night on the way home I stood idly calculating the price of fuel per (imperial) Gallon, we've been buying fuel in litres in the Britain for 20 years now but we still think of fuel consumption in miles per gallon, like my grandmother converting prices into Shillings to the day she died (10 years after currency went decimal) we still go back to pricing in Gallons. The little display on the pump last night said 132.9 pence per litre; as the displays ticked round to  64 litres and £85, I tried to multiply 132.9 by 4.54 to get price per Gallon. "Call it 4/3 x 4.5 ... thats £6 a gallon !"... " now without the rounding is that just over or just under ?" Queuing to pay I got my phone out and used the calculator £6.03. For readers in the US, your gallons (and pints) are 20% smaller than ours,and with the pound at $1.97 that makes UK diesel abut $9.50 per US Gallon (Petrol/Gasoline is about 10% cheaper)

    For the at least the last 10 years, governments have been raising the cost of fuel above the rate of inflation to try to encourage us to use less of it. (I don't want to get into party politics here, I think the Conservatives started it and Labour thought it was a good idea and continued the policy). There are now differential rates of Vehicle Excise Duty on based on emissions. Those who think of their fuel in gallons remember when this flat rate tax was called the "Road-Fund licence" but for years governments have been using fuel and VED as a way of raising money to pay for anything but roads. I've heard politicians from all the main parties arguing for huge rates of VED for the most polluting cars. Since I have a "clean-diesel" which does about 50 Miles to the Gallon it doesn't affect me, and in any event as a company car driver I'm insulated from rates of VED, so I have no particular interest to turn me against such a plan. But  like calling for extra taxes on "The rich", it's easy politically: if you hit people at one extreme you don't hit the other 95% of people who might vote for you. It doesn't take a mathematical genius to see that someone whose car only does 20 Miles per gallon but only drives 40 Miles a week, uses less fuel than someone whose car does 50 to the Gallon but drives 400. Should they pay tax on fuel used or on their vehicle's potential to pollute ? Increasing the cost of owning an inefficient car might result in some of them being scrapped early - which takes money out of the economy, and results in more demand to manufacture new cars - a process which also uses a lot of energy.  Logic would say scrap VED entirely and raise the same amount of tax from extra fuel duty. Those who use less fuel than average would be better off, those who use more would be worse off. The whole government bureaucracy dealing with VED could be scrapped (saving more money) and the VED tax disk could be replaced with something issued the car's insurers to show it's paperwork was all in order.  The political problem with such a policy is that everybody sees their fuel price go up and has to pay more every week, reminding them the government has done something unpleasant.

    The key, of course, is to find ways to make fewer journeys. and to use more efficient forms of transport for the ones we do make. As someone wrote
    "Here in my Car,
    I feel Safest of all,
    I can lock all  my doors,
    it's the only way to live,
    In cars"

    Of course he it might not have scanned so well to say "I can pick my nose" , "I can shout at the radio" , "I can listen to music without headphones" , "I can set the temperature to what I want" etc. Some of us might be priced out of our cars and into using car-shares or public transport. But if we didn't all go to the office every day, the office could be smaller and the saved Journeys would save money, time and pollution. Think of that next time you curse the traffic or the cost of filling up.

  • James O'Neill's blog

    A little bit of Microsoft Honesty.

    • 3 Comments

    image  I like Vista. And I like the fact that with Ultimate I can have a 64-bit, domain joined , Tablet enabled, Media Center PC. (IN XP these were 4 products). I like media-center.  But one aspect of media centre drives me nuts, and that's its determination to keep a ton of free space and to over estimate the space it takes for any given recording. I wanted to record 2 hours of a movie tonight which would have taken about 2.5GB of space.I have 8.2GB free and Media center wouldn't record. By the time I'd shifted some recordings off the PC the start of the show had come and gone

    This evening I had two problems. I  suspect because Media Center brought the machine out of sleep to record something yesterday when it was in the car and the TV stick was disconnected, the Windows Media Center Receiver Service got stuck. The symptoms of this are that the Media Center program believes there is no tuner attached. I had to kill several things before finding it was the service and along the way I  killed the "E-home tray applet" which media center uses to tell me when what it's up to.

    So when I tried to start a recording manually, the message box on the left appeared. I have to admire whichever of my Redmond colleagues put this message in. What I'm curious about is everywhere else "Center" is written with an ER as in US English. Here it's written with an RE as in British English. I preferred this to "General Failure, Error 4096 has occurred" style messages but  somehow I doubt if it's a trend.

  • James O'Neill's blog

    More on the Hyper-V API

    • 2 Comments

    In which we see how to set the number of CPUs

    I started with getting MSVM Computer System objects - which I showed back in February. With these objects I can ask for the state of the VM to be changed to Running, Stopped or Saved.

    To do things in a proper Powershell Style I re-wrote and re-wrote my functions so I have GET-Vm (which returns one or more VM(s) by name), Choose-VM, which puts up a list and returns one or more VM(s). Plus Start-VM, Stop-VM and Suspend-VM. Over various iterations these have moved from demanding a single MSVM Computer System object, to accepting an or object or display name, then to accepting and of array either, to allowing input to be piped in. Since Stop-VM is a bit brutal, that same February Post showed using the ShutDown integration Component

    Next I moved onto the Msvm_ImageManagementService, and a few weeks back I looked at how Virtual Hard disks can be created , mounted and Compacted.

    From there it was on to the related idea of Snapshots which I covered here and here; Snapshots are handled through the Msvm_virtualSystemManagementService. This is actually a very important WMI class. I mentioned Taylor's post which shows how to manipulate the Exchange of Key/Value pairs (the Host's KVPs are managed through this object). But there are 6 other methods I want to introduce here they are Create-, Modify- & Destroy- VirtualSystem and Add, Modify and Remove Virtual System Resources.

    Creating and Modifying work in the same way. Identify the machine (unless it is being created) and pass a block of XML which describes how you want the machine, or the resource attached to it to be. If you're think ahead and saying "Can I dump that XML out to a file ?" you can: both the Virtual System Management Service WMI object and the MMC console provide interfaces to Export or Import the Machine.  There are quite a lot of things which we want to be able to manipulate.

    • Legacy Network Card
    • VM-Bus Network Card
    • VM-Bus SCSI Controller
    • IDE DVD Drive
    • Virtual DVD Disk (which is inserted into the drive)
    • IDE Hard drive
    • SCSI hard drive
    • Virtual Hard disk-image (inserted into the drive)
    • Memory size
    • CPU cores and reservation
    • The VM itself

    And for each of these we can get the XML by

    • Building it up from Scratch
    • Reading it from a file
    • Getting the existing value from WMI (for modification)
    • Getting a default from WMI (for creating)

    The first 2 are usually a pain, so typically the process goes:

    1. Get a ResourceAllocationSettingData (RASD) object
    2. Modify one or more of its properties.
    3. Covert it to XML formatted Text,
    4. Pass the XMl as one of an array of arguments to one of the Methods of the Msvm_virtualSystemManagementService.

    For example: here's how we set the number of CPUs - we get a variation on the generic RASD object, the Msvm_ProcessorSettingData object for the VM in question.

        Filter Set-VMCPUCount
    {Param ($VM , $CPUCount)
    $procsSettingData=Get-WmiObject -NameSpace  "root\virtualization" `
    -query "select * from MsVM_ProcessorSettingData 
                                    where instanceID like 'Microsoft:$($vm.name)%' "
    $procsSettingData.VirtualQuantity=$CPUCount
    $SettingXML=$procsSettingData.GetText([System.Management.TextFormat]::WmiDtd20) $arguments=@($VM.__Path, @($SettingXML) , $null) $Result=$VSMgtSvc.PSbase.InvokeMethod("ModifyVirtualSystemResources", $arguments) if ($Result  -eq 0) {"Success"} else {"Failure, return code: $Result "} }

    [Update. There were a couple of bits of PowerShell 2.0 in the above. In 1.0 you can't call the .InvokeMethod  method of a WMI object directly, you have to call it via .psbase and .PATH property doesn't exist, you have to get to the path with __Path, not .path.path]

    The process is almost identical for memory, except get the Msvm_MemorySettingData object and set 3 properties named, .Limit, .Reservation   and VirtualQuantity which are all set to the desired memory size in megabytes

    In the next few posts I'll look at using the RASD objects to add disks and Network cards, plus how we can create and configure the VM itself.

  • James O'Neill's blog

    Eggsactly the wrong way to go about things.

    • 1 Comments

    We've had a mail thread running about what happened to Steve Ballmer in Hungary.  If you haven't seen in on Eileen's blog just search for "Ballmer" on youtube and you can watch what happened. To save you the trouble,   Ballmer was at Corvinus University to address students and receive an honorary degree. A local man stood up from the audience and accused Microsoft of stealing millions of dollars from the Hungarian people, and then threw three eggs .

    Now I'm not going to share all the internal information partly because it talks about Steve's security arrangements, but I did want to call out a couple of things. Steve has security who travel with him and they didn't pounce on this guy and rough him up (perhaps our PR people saw the Walter Wolfgang incident at the Labour Party conference ... ).Steve could have pulled a Prescott and gone after the guy himself.  Instead he seems to come out of this looking pretty unflappable: I'm told he was very nice to everyone about it, joking that back home the guy's aim would have been better. 

  • James O'Neill's blog

    The long tail, Music and the small bookshop

    • 1 Comments

    I've talked about the millennial thinking before. I've heard it  said that the "iPod Generation" don't think about "Current Music" vs "Old Music". When I bought LP records there was never much back-catalogue in the shops. Growing up in Brighton there were second hand record stores which you could trawl if you wanted something which was long gone, but something which had gone out of the shops recently didn't show up. But, if you get most of your music by downloading, then there's no division into current and old. Music gets added to servers but it could be back catalog just as easily as it new releases - and server capacity can increase in a way that shelf space in a bricks and mortar shop never can. I recently went to see Gary Numan re-touring the 1979 Replicas Album. The audience was a mixture of 40-somethings who remembered the album from new, and students who'd discovered Numan from the various people who link to him and know Replicas from downloading it. At Radio 1's big weekend last week (great bit of Deep Zoom, by the way) - it was young fans who complained that Madonna didn't play her early stuff (we're talking 1983 music here - before some of them were born ).  Having heard Annie Lennox on Desert Island Disks this morning her Music from 1982/3 sounds every bit as good today [she picked the Beatles' Penny Lane as one of her 8 songs - I'd love to know what their download stats are like]. There are plenty more examples if you look, and of course this is what the idea of the long tail is about. Good music, (and good movies and good books too) will continue to find a market forever if you don't have to take them off the shelf. The same idea applies to blogs, Wikis and a lot of other "user generated content". If this blog were a newspaper column, it would appear, be read and disappear. As a blog the text remains - potentially forever, and thanks to search engines is discoverable and consumable - there are plenty of ramifications in that.

    Two years ago now a couple of friends of mine announced they were going to open a bookshop. Part of me envied them, because I worked in a small bookshop before getting my first "proper" job after University and I remember it fondly. Part of me remembers running a business and the stress that went with it and would say "Never again"; that part also wondered if they had the resources to cope with a slow start or any spell of poor sales.  And part of me said "are they crazy ? Going up against Amazon etc on-line, and only a few miles from Oxford where book buyers are very well catered for".  It's pretty obvious that if you're going to make a success of it you can't compete on selection or price with the Oxford stores - much less with Amazon, but if you can make a place where people like to shop they will reward you with their loyalty. How to make such a place is a the challenge. Well Nicki and Mark seem to have cracked that because this week they picked up the Booksellers Association New Bookshop of the Year award. I'm sure it helps that they have a blog, but you have to more than that - things like this for example. Well done folks.

  • James O'Neill's blog

    On Ninjas.

    • 1 Comments

    andrew2 Over the weekend one of the many Davids I count among my friends mailed me a curious job title from his organization. Yesterday, in one of those moments of serendipity Viral told me about one of the guys in Redmond who has the job title of "Zune Ninja" - he explains how the the title came about here. A while back I mentioned Tom Lehrer, and Plagiarize. Viral's good friend James Senior is the one whose name is cursed, when we found out he published first.

    So while we're on Ninjas, I should say that when I drew the team cartoons using Janina Köppel's Excellent SP-Studio I couldn't find a way to capture Andrew so I tried doing him as SQL Ninja. This seems like a good time for that cartoon to come to light.

Page 1 of 2 (27 items) 12

May, 2008