Monday, January 21, 2013

Building A Hyper-V Test Lab on Windows 8 – Part 3 Creating VMs

This the third part in a multi-part set of articles. See the first article for the start of the set and to understand better what this is all about – see here: http://www.tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows-8.html. And to see the prior article on creating a reference VHDX see here: http://www.tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows.html.
 
Building a VM
The overall purpose of my VM Build scripts is to create and configure a set of VMs in a test environment. In the last article, I showed how you can create a base or reference disk. In this article, I show how you can take that base disk and create both a differencing disk and a VM that uses that new disk.
 
Each VM created gets a customised Unattend.XML file, which is stored on the differencing disk, once that disk is created. Thus, when the VM is started, OS installation is completed using the XML file. This allows me to do some simple things, like kill the firewall, set the right language(s), etc.  Creating this file was one of my early stumbling blocks!
 
Unattend.XML
From the earliest days of Windows NT, you could create an Unattend.txt file, put it on a floppy disk, insert the floppy into your system then install the OS from the CD. That enabled Windows NT setup to get the details of the installation coming from the Unattend.Txt. I did a lot of that in then NT 3.5/3.51/4.0 days. But with Vista, Microsoft shipped a totally new setup method, with WIM files and with Unattend.txt replaced with (a more complex) Unattend.XML. Pretty much everything I knew about unattend.txt files goes out the window.
 
A key objective I had in creating these build scripts was to avoid having to know too much about these XML files. I got a ‘starter’ copy form my good pals at Lab Center in Stockholm and have tweaked it (removing things I don’t need) and creating useful default settings for things (e.g. keyboard).
 
I really wanted to avoid becoming a deployment wizard and use a generic Unattend.XML file. But sadly, that objective proved to be a little unreasonable, but I’ve tired hard to minimise the number of things configured in the XML file and do as much as I can via PowerShell scripts after the OS has been installed.
 
Using Unattend.XML files is pretty simple, as long as you understand both the Windows build model and the components you can add to windows. To use the Unattend.XMO file, you create/configure the XML file, save it on the differencing disk and add the differencing disk to the VM. This way, the unattend.XML file guides Windows Setup to create the VM as you need it.  Subsequent scripts that configure the VM further (e.g. adding application specific windows component, adding applications and features, etc.).
 
In the Unattend.XML file, I currently specify 14 components in three passes as follows
 

Pass

Component

The effect of this component

Generalize Microsoft-Windows-Shell-Setup Specifies that Sysprep should not remove any icons from the Quick Launch toolbar
Specialize Microsoft-Windows-UnattendedJoin Specifies the domain to join and credentials needed to join or whether to just ‘join’ a named workgroup
  Microsoft-Windows-Shell-Setup Specifies Computer name, registered organsiation and owner, and time zone
  Microsoft-Windows-IE-InternetExplorer Sets home page to blank and whether to disable the run-once wizard
  Microsoft-Windows-Deployment Enables local administrator account
  Microsoft-Windows-International-Core Specifies Input Locale, System Locale, UI Language and UserLocale. The input locale sets an initial keyboard layout.
  Microsoft-Windows-TapiSetup Tapi settings
  Microsoft-Windows-IE-ESC Turns off the IE security settings
  Microsoft-Windows-TerminalServices-LocalSessionManager Enables Terminal services connection to the VM
  Networking-MPSSVC-Svc Turns the firewall off on the VM
  Microsoft-Windows-TCPIP Sets TCP/IP settings, including IP address, subnet mask and default gateway
  Microsoft-Windows-DNS-Client Specifies the DNS Server IP address
OobeSystem Microsoft-Windows-Shell-Setup Specifies local administrator password, whether to hide the EULA pages plus sets the time zone
  Microsoft-Windows-International-Core Specifies a 2nd language to be setup for this VM
 
The Create-VM function
The core aspects of the VM creation is done with the Create-VM function. The function takes parameters including the VM name, the path to store the VM information for Hyper-V, the path to the reference disk, what network to use, how much memory to set, which Unattend.XML file to use and the IP address, subnet mask and DNS Server Address.
 
The details of the VM created is determined by what is in the Create-VM function, details in the the Unattend.XML file and some details set by the call to the create-VM function. For example, the keyboard settings used are set in the XML file only, whereas the use of dynamic memory is set only in the Create-VM function. The IP address, on the other hand, has a default set  in the XML (10.0.0.250/24). The Create-VM function, however, overwrites this address with the IP address/subnet mask specified  in the call to Create-VM.  The parameters specified on the call to Create-VM are used to update the Unattend.XML file stored on the differencing disk and used to install the OS.
 
I use two XML files – one is used to create a stand alone server the other to create a domain joined server. I use the former to create DC1 and once DC1 has been promoted to be a DC, the later XML file is used to create servers that are domain joined. Both XML files, on the other hand, set keyboard layout
 
This approach of setting some installation options in the XML and others via the function (and resulting in updated XML) seemed to be a good compromise. I only implement parameters to Create-VM that need to be differ3ent in different VMs, whereas installation options
 
Creating the VM
The task of creating/building the VM is performed by the Create-VM function and involves the following steps:
  1. Creating a differencing disk – this is the ‘difference’ between a reference or parent Vhdx  and  the disk. 
  2. Creating a VM in Hyper-V.
  3. Adding the differencing disk into the VM.
  4. Mounting the VHD on the host computer.
  5. Based on a pre-built Unattend.XML, creating a customised Unattend.XML file and saving it to the on the mounted VHDX.
  6. Dismounting the VHDX from the host
  7. Setting VM settings including memory, startup actions etc.
  8. Starting the VM.

Once the VM has started, windows setup proceeds to install Windows as per the Unattend.XML file. The creation of the VM itself takes just 20-30 seconds, followed by the actual installation which takes 10-15 more minutes (and more if you are doing multiple installations in parallel).

The Created VM
The VM created by the Create-VM function will either be a workgroup VM or a VM that has been joined to the domain, as specified in the Unattend.XML file. This VM will be fairly vanilla with only a few options specified (as noted above). There are no extra applications loaded, and the Unattend.dj.xml file only ‘works’ once you have the DC up and running.

The Create-VM script takes around 27-30 seconds to create and start the VM in Hyper-V. On my WIn8 laptop, it take a further 5 minutes to complete the creating of the first DC.

Example
Once you have the reference disk, you can call the Build-VM function like this:

$ref    = …   # Path to the reference disk
$Path   = …   # Path to where to put the VM and differencing disk
$unadj  = …   # Path to Unattend.XML
#     Now Create the VM
Create-VM -Name "Srv1"  -VmPath $Path –ReferenceVHD $Ref  -Network "Internal" `
          -UnattendXML $unadj -Verbose -IPAddr '10.0.0.30/24' `
          -DNSSvr 10.0.0.10  -VMMemory 512mb

You run this script ON the Hyper-V server. Once the Create-VM function completes, which takes between 20-25 seconds in my case, Hyper-V starts up the VM and completes the installation of the OS inside the VM. The complete installation takes 20 minutes or so (depending on your system, how much RAM you give the VM, the speed of your system, etc.). Once the setup is complete, you can move on and configure the VM with application and application settings.

Where are we on this journey?
In the these first three blog posts, I’ve set out the objectives of a VM Build module for building VMs and the two core functions/scripts. The two scripts create a base VM disk, a differencing disk and a VM. Each VM is customised a little in the call to Create-VM – in effect creating a base VM. Once this VM has been created, you can then load additional applications and Windows features (e.g. making the DC a certificate authority). In the next episodes of this set of blog articles, I’ll start looking at the scripts that add those applications and features. And I’ll share the interesting things I’ve discovered along the way. I’ll also publish the scripts and the unattended XML files.

 

 

 

 
Technorati Tags: ,,

Viewing PowerShell Function Definitions in the ISE–Part 2

Last Friday, I published an article about a neat script I’d come across. At the end, I mentioned it would be nice to extend this to enable me to highlight a function name I’m calling in code and either use a menu item or short-cut keys to get the definition up.

Well, I spend several hours today playing and have done just that. Yesterday, I polished up the code a bit and published it over on my PowerShell Scripts blog. At home, I’ve incorporated it into my personal ISE module and it now loads every time I start up the ISE.

The script, as extended, defines a function (Open-FunctionInISE), then adds it to an ISE menu. The function takes input in three ways: you can specify the function name to open, you can highlight the function name in an open edit window and use either short-cut keys or the ISE menu. And if those fail, the function prompts for a function name. I’ve also taken the liberty of renaming the function to be, hopefully, closer to best practice naming!

In converting the function, it was interesting working with a single function that could take input from the pipeline, from the command line of via selected ISE text (and which prompts for a function name if all those fail). In doing the conversion, changed the parameter from a string array to string, which felt nearer to the way I see the script being used. I might play around a bit with the script and add that back in. To simplify such changes, I’ve left the function to operate in the Process block, but I have pulled out the enumeration of objects within each process block.

Another thing the extended script did was to add the function to a menu item in the ISE. That turns out to be easy. Before the script adds the function to the add-on menu, it checks to see if it’s already been added (as might happen if you decide to edit the function and start running it!). Of course, if you already have the menu item created, to make changes in the function itself, just comment out the menu addition code. Or use the function to bring the function definition into the ISE, make your changes and re-run just that script (remembering to persist any changes you decide to make!).

Thanks to the original author of this script (Cookie.Monster) for giving me something fun to do on a Sunday afternoon. Comments most welcome.

Technorati Tags:

Friday, January 18, 2013

Microsoft PowerShell V3 Course (10961) Announced

Microsoft’s just published details of it’s ‘official’ course on PowerShell V3. This is being written by Don Jones, so it should be a pretty solid course. I look forward to teaching this course, which is meant to go live in May. I don’t know who the TE will be, but I’ve certainly volunteered!

The course looks to be a good beginners look at PowerShell V3. As the Microsoft web site points out, this will be a 200-level look and is not intended to teach much about scripting or programming. For those IT pros who have never seen PowerShell, this looks to be a very good course, although it will be pedestrian and will not be overly technically deep.

I have my own PowerShell V3 material and have been teaching V3 for some months. My material is more condenses, and at a higher level (300-400), and I have more advanced material for those needing more specific PowerShell related skills such as using PowerShell to manage XML and SQL. One (if I do say so myself) awesome aspect of my material is that delegates build their own VM test environment using PowerShell scripts (i.e. ones I started blogging about this week).

I am looking forward to the new course – which should be great fun to deliver as well as being able to challenge delegates with more advanced material as needs be.

As soon as I get the courseware and am able to, I’ll post more about this course.

Viewing PowerShell Function Definitions in the ISE

I came across a neat script, recently posted to Microsoft's Script Center. The function, Open-ISEFunction.ps1 takes the name(s) of function(s) that are currently defined and creates an ISE edit tab for each function.  It’s pretty simple in that it jut grabs the function definition from the function: drive, wraps the definition in a function/script block, then opens and adds the definition in a new ISE window.

If I get time, I might extend this function for the ISE into a menu item. The expanded function, which could as a menu item have a command key short-cut, could take any selected text and try to open the module of the same name. I’d also like to add a couple of comments at the start that might help.

 

Technorati Tags:

Thursday, January 17, 2013

PowerShell Profile Files

As a power user of PowerShell, I have heavily customised my environment, through the use of profile files. I create additional PS drives, define key variables and aliases, create credential objects for my test labs and local domain, configure the title bar to make the user I’m running PowerShell as a bit clearer, etc.  My ISE profile file also imports a few modules which add menus to the ISE console. I rely on my profiles – and even when teaching. I’ve put up a base console and ISE profile on my DropBox account and have loaded the basic files there.

But when it comes to running background jobs or doing remoting, those profile files are not, as it were, in play. Mike Pfeiffer, over on Don Jones (old) blog, writes an interesting article about this very point. While the post dates from 2011, the relevance of profiles is all the more these days as remoting becomes much more prevalent (and the ‘missing’ profiles become more of an irritation!).

This article is worth a read!

 

Wednesday, January 16, 2013

Building A Hyper-V Test Lab on Windows 8–Part 2 Creating a Reference VHDX

This the second part in a multi-part set of articles. See the first article for the start of the set and to understand better what this is all about – see here: http://www.tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows-8.html.
Base/Parent Disks in Hyper-V
With Hyper-V, you assign one or more virtual disks to a VM. One trick, borrowed from VMware, is the ability to create parent and differencing disks. The parent disk is a normal VHDX drive built out to a certain point. This can be a completed installation, or a partial installation. The differencing disk is then the difference between the base or parent virtual disk and the contents of the combined virtual disk at some later point in time i.e. after installation. Thus if the base disk was the uninstalled image, the differencing disk would only hold the changed made since installation.
 
On my Windows 8 box, the reference disk is 8.2GB while each of the differencing disk are between 2-3 GB.  In all the 4 VMs currently in a configuration I am testing takes up around 23 GB. Were I to create a full separate drive for each VM, I’d need nearer to 40 GB, so the space reduction is useful!
The way I use this in my labs is simple. I create a base disk which contains the uninstalled image of Windows server using the Create-ReferenceVHDX script. Then I use that reference disk in the Create-VM function that actually creates and starts a VM.
Creating a Reference VHDX using PowerShell
Creating the reference VHDX is pretty simple. The Create-ReferenceVHDX.PS1 script file creates a function, Create-ReferenceVHDX, then at the bottom invokes that function to actually create a reference VHDX. In my testing, it takes around 8 minutes to create the reference disk, most of which is taken up by DISM.EXE applying the relevant image to the base disk.

The creation process is as follows:
  1. First, we load the DISM module.
  2. Next we mount the ISO image used as the basis for the VHDX into the host machine (I.e. the Hyper-V host). The name of the VHDX is passed as a parameter to Create-ReferenceVHDX. We have to get the volume object to then get the drive letter where the IOS is mounted.
  3. We read the install.wim from the appropriate spot on the DVD and get the user to specify which installation contained in the WIM is to be used as the basis for the base disk. I use Out-GridVIew for this, but you could I suppose just take whatever the last option is (or the first) as needed.
  4. The function then creates a new VHDX file to hold this image, which is then initialised. Sometimes this throws up a dialog box but that can be safely ignored.
  5. DISM.exe then runs which applies the chosen install image onto the VHDX. This is quite a long process and can take 10 minutes.
  6. Once the image is laid down, BDCBoot ensures the disk can be booted from.
  7. Finally, the VHDX is dismounted form the local host and the function finished.

See the script for the details of how these steps are carried out!


Using the Create-ReferenceVHDX Function
Using the reference VHDX is pretty simple – three lines in all:

$Iso          = …    # Path to Server 2012 DVD    
$Refvhdxpath  = …    # Path to where the reference VDHX is to go
Create-ReferenceVHDX -Iso $iso -RefVHDXPath $RefVHDXPath  -Verbose

Using the Reference VHDX
Once the reference VHDX is created, you can use it as the basis for creating differencing disks you can then insert into VMs. See Part 3 of this tutorial to see how to do that.

Getting the scripts
The scripts are all published to a zip file: http://www.reskit.net/powershell/vmbuild.zip. Use carefully and enjoy!

Monday, January 14, 2013

Learn PowerShell Toolmaking in a Month of Lunches – A great new book!

Over the recent holiday period, I got my hands on Don Jones and Jeff Hick’s latest book: Learn PowerShell Toolmaking in a Month of Lunches, published by Manning (see: http://morelunches.com/toolmaking.html for details of the book).

For anyone wanting a deeper set of PowerShell skills, this book is great. It firstly covers the journey from writing simple scripts to writing re-usable functions and modules. In doing that the book also covers things like help information for your functions, using work flows, globalisation, etc.

If you think you know PowerShell, then you really should read this book as you probably will still learn things (I did!). And if you are a novice with PowerShell, this book will teach you good practice.

As with all Don’s books, this one is easy to read, the examples work and the flow is easy to follow. The authors’ viewpoints and biases are also on display. You can easily spend your lunch break each day reading another chapter and experimenting with the techniques shown. Or as I did, sit down and read it all the way through in a couple of days. Either way this is a very good book for those wanting more and deeper PowerShell skills.

As my quote on the cover of the book stays: Yet another great book from PowerShell legends Don and Jeff.

Technorati Tags: ,

Sunday, January 13, 2013

Building a Hyper-V Test Lab on Windows 8 – Part 1

This is the first part of a multi-part blog article on a set of scripts to create VMs using Microsoft’s Hyper-V on both Windows 8 and Server 2012.

Note: this page is being updated along with others in this set as I slowly get all this documented and published.

Background

For many years, I’ve used virtual machines heavily. The articles, courses and books I write rely on VMs for their content. I’ve lost count of the number of domains I’ve built, re-built, broken, fixed over the years. 

The only downside is that I was regularly building and re-building the systems by doing creating a new VM and installing the OS from scratch. This was slow and tedious as well as somewhat error prone.

What I needed was a good, reliable system of creating sets of VMs and configuring them. The base set of services I want to be able to install and use was not that long: the OS (with AD, ADCS, DHCP, DNS, File Services), SQL, and Exchange.

Now that I have these scripts working, or nearly so, I am amazed at how much easier it is to create a set of VMs for particular purpose (e.g. write an article, create a class, build a demo for a talk). I am also finding others that have similar needs. I hope others find these scripts useful!

Building VMs Using Scripts

In the autumn of 2012, I, along with super-star MVP colleague Niklas Goude, started running PowerShell Geek Weeks in Stockholm. A lot of fun – 5 days of going as deep as we can with PowerShell. A key part of the Geek Week adventure is for the delegates to build their own environment AND to be able to take away the tools to re-create this environment at home.

I spent quite some time building some basic scripts – and encountered a lot of dead ends along the way. The first time out was a limited success – limited in that some pieces did not fit together well but a success in that it taught a lot of cool PowerShell features and showed us where we needed to do more. It also helped me to refine the real objectives the tools had to meet. Thanks goes to Mikael Nystrom for helping me with a good starting Unattend.XML!

Objectives of the VM Build module

My main objectives of these build tools were:

1. To enable someone with fairly limited PowerShell skills (or greater!) to use the the scripts simply and flexibly in the classroom and later.

2. To enable building out of a small farm of up to say half a dozen servers with minimal effort.

3. To enable extensibility, in that one could add more scripts to refine the configuration (e.g. adding a script to implement a failover DHCP).

4. To encode things like domain/forest names, user ids, passwords and IP address information to a given standard but make it not too difficult to change that.

5. To avoid the user having to use too much of the new automated setup approach.

6. To keep the use of disk space to a minimum.

The Architecture

The basic architecture of what I am trying to build is shown here:

image

 

The idea is simple – a single reference, parent, disk with a number of separate VMs based on differencing disks. This approach hits objective 6, and enables a simple solution to objective 4.

The Scripts

The key scripts here are as follows:

  1. Create-ReferenceVHDX – this script creates a parent VHDX based on an image from the Install.WIM from a Server (or client) installation DVD.
  2. Create-VM – this script creates a differencing VHDX, based on the reference VHDX, and creates an updated Unattend.xml file, stores this on the differencing drive. The script then starts the VM which then installs Windows onto the differencing disk. You run this script to create the VMs and VHDXs for DC1, Exch1, SQL1, SRV1, SRV2.
  3. Configure-DC1-1 – this script turns the first VM, DC1, into a domain controller in a new forest.
  4. Configure-DC1-2 – this script configures DC1, post installation as a DC. This includes adding and configuring DHCP and creating some users in AD.
  5. Configure –DC1-CA – this script convers DC1 into an Enterprise Root CA, and creates a web responder, complete with SSL support for the /Certsrv application.
  6. Configure-Exch1 – this script configures the Exch1 VM, including installing Exchange 2008 on the Exch1 VM.
  7. Configure SQL1-1 – this script configures the SQL server VM, including installing SQL server itself.
  8. Configure-SRV1-1 - Configure-SRV2-1, these scripts create a pair of application servers, including adding all of the RSAT tools and IIS.
  9. Utility Scripts – these include Set-DVDDriveOnAll (sets a particular DVD/ISO to be in the DVD drive of all VMs), Set-LanguageOnAll – sets the administrator logon have a particular kb layout for all vms, Set-NetFrameworkCoreOnAll (adds the base .NET onto all systems – which is needed for PowerShell V2).

These scripts are now online and you can get them from http://www.reskit.net/powershell/vmbuild.zip.

 

What’s Next?

There are several next steps:

  1. I’ll publish each script both to the PowerShell scripts blog (http://pshscripts.blogspot.co.uk) as well as publishing details of each scripts here. IN publishing the details here, I’ll explain what each script is doing and why I did it that way. As ever, comments are welcome – and may cause further updates to the script set!
  2. I’ll update this page with pointers and anything updated as I complete this set of posts.
  3. Package these scripts up as a downloadable module. Right now, these are just a bunch of scripts and some XML – making a proper module out of it is high on my agenda.
  4. Do a better job of centralising the variables across the scripts – things like user name, password, domain name, etc. I had in mind an XML file with all the key stuff in just one place!
  5. Take feedback and refine. Comments on these scripts are most welcome.

Summary

With the release of Server 2012 and Windows 8, building a set of Hyper-V VMs is now easier than ever – and these VMs can easily be moved from server to client and back as needs dictate. The set of scripts I’ve created have helped me create lab environments quickly and easily and may help you too.

Comments most welcome!

Catching Exceptions in PowerShell

In a recent class, I was discussing how you can deal with exceptions that occur when PowerShell hits a terminating error. Doing this allows you to gather information around events that should not have happened – but did! I wrote up a blog article a couple of years ago which describes error handling in PowerShell that describes how you can catch errors.

The question was not so much, how do I do it, but what are the specific errors you can actually trap. For example,

Trap [System.DivideByZeroException] { 'whoops - divide by zero'; }
$z = 0
1/$z
"next'

or

Try {
  $z = 0
  1/$z
}
Catch [System.DivideByZeroException] {
   
'whoops - divide by zero' }

That bit is fairly easy.  But do I what I can trap for? Turns out, answering that question is relatively easy as long as you know the .NET exception names you wish to trap or catch.  Within .NET, an Exception is a specific terminating error that I can explicitly catch. In the above code fragment, the code catches the specific Divide by Zero exception.

I have just posted a script to my PowerShell Scripts blog which does this. The script is posted at: http://pshscripts.blogspot.co.uk/2012/12/show-exceptionsps1.html. If you download it and run it, look in the right hand column - those are the exceptions you can catch.

To find more about the individual exceptions, MSDN is your friend.

Friday, December 21, 2012

PowerShell V3 Training

My main ‘day’ job is training, running courses in a variety of (mainly) Microsoft technologies including Lync and PowerShell. I teach the official Microsoft courses (I helped write both of them!), and have my own material that I’ve been running across Western Europe. With the release of PowerShell V3, I’ve created a new course which I was able to run for the first time this week on Trondheim Norway. It was the last week of work this year – and what a great week’s been – on several levels.

The first time I teach a newly written course – there are always things I can do better. There are the inevitable typos to correct, flow issues to work on etc. But as I de-stress from the long trip home, I reflect on the fact that it went well, the labs worked, well mostly, and the students had a great ride.

Whenever I teach ANY course, I have three objectives: to have fun, to learn more and to meet the students objectives. My view is that if we’re not having fun, not enjoying the week, then folks aren’t learning – which is NOT a good thing. Having fun and being (as the instructor) challenged is important. Meeting student expectations is vital, but having fun is cool too.

Well – this week I sure had fun. I had a great crowd of folks with varying skills who all wanted to learn more about V3. The folks were great – and being in Norway was fun. As to learning – man did I learn a bunch of stuff this week. And from the mails I’ve had the students all enjoyed the event. I even convinced one student to use Twitter – so hello @PowerShellGirl!

As part of the course, there are a number of VMs that we use  in the lab exercises. Rather than pre-build them, I had the students do the build. Using PowerShell of course. I have a nice set of simple build scripts that create a base VM image, and then create a primary DC, a secondary DC, and several member servers. As soon as I get a few hours to do it, I’ll publish these scripts – I’m sure they’ll be useful. I’ll also be improving the scripts to include installation of SQL, Exchange and a Certificate Authority.

Having scripts that create VMs has been a long term goal of mine. I so often need to create one or two (or more) VMs for use with an article/book etc. – building out a test infrastructure manually is so boring. The combination of PowerShell and Hyper-V make it relatively easy to create a lab environment that also shows students the real power of both Server 2012 and PowerShell V3. The more I work with Server 2012 (and PowerShell!) the more impressed I am with the potential.

Server 2012 is by far the best server OS Microsoft has ever produced. I just wish the idiot who insisted on the Windows 8 bi-polar interface was fired. Oh wait – has been! And that’s a good thing.  Of course, for a few dollars, I got Start8 which makes Sinofsky’s folly a dim memory. I can now get on and enjoy this truly magnificent OS.

Being able to show students how to manage the server using PowerShell is truly a joy. There is true beauty  in looking at many of the scripts I’ve put together for my course. I wonder if senior management really understand the true value of PowerShell? The power of many, the simplicity one  - it may be a marketing slogan, but it sure resonates for me. Being able to just invoke a script block on multiple machines in a couple of lines of script is just plain powerful – and very cool.

Well - 2013 is just around the corner and I am really looking forward to working more with both PowerShell V3 and Server 2012 in the coming year. As I write this blog, I’m listening to  Fleetwood Mac (Rumours) : “Don’t stop thinking about tomorrow – yesterday’s gone”   How apt the lyrics are. It’s been a great year – I’ve met some great people and now I have some great tools to work with. I just can’t stop thinking about tomorrow. 

Merry Christmas all – and may 2013 be a great year for you all.

Friday, November 23, 2012

Saving PowerPoint slides to PDF with PowerShell

Today, I’m having a bit of a catch-up day. One task I’ve been meaning to do for a while was to covert some PowerPoint slides to PDF for distribution and printing.

The basic task of converting a presentation to PDF is simple in PowerPoint. First you start PowerPoint and open the presentation. Then you save it as PDF using the Save-As dialog (and close PowerPoint).

The old saying if you have to do some thing more than once, write a script kicked in and so I did (write a script!). In theory, it should be relatively trivial to write a script that did just that. And once you know the complex PowerPoint object model, so it was! The full script is over on my scripts blog at: http://pshscripts.blogspot.co.uk/2012/11/convert-pptxtopdfps1.html.

It turns out that writing the script was a bit of a walk on the dark side, as in working with com and the Office COM objects. While what I wanted to do was simple, I needed to do it the way that PowerPoint's COM object wanted to – which was  bit different to working with some other API sets.

Working with Office, in particular the Office object model, from PowerShell is a bit painful. The PowerPoint object model is huge. When you instantiate the PowerPoint.Application object, you get a new object that is extremely rich and deep. You get loads of methods and properties. Many of these properties are themselves objects with methods properties (that can also be objects), etc., etc., etc. Since they are COM, the normal goodness of .NET reflection (i.e. Get-Member) is missing. Using a good search engine and applying a little ingenuity is the key!

In terms of getting this to work, the first issue I hit was the need to add some assemblies into PowerShell, like this:

Add-type -AssemblyName office -ErrorAction SilentlyContinue
Add-Type -AssemblyName microsoft.office.interop.powerpoint `
          -ErrorAction SilentlyContinue

Next, you open PowerPoint by instantiating the PowerPoint.Application COM object, and making it visible is relatively easy:

$ppt = new-object -com powerpoint.application
$ppt.visible = [Microsoft.Office.Core.MsoTriState]::msoTrue

An important point here is that you can’t use $True here to make PowerPoint visible. The ‘true’ you have to pass to PowerPoint is based on the enum, not on the normal .NET Boolean true. Finding these enums’s full name for PowerShell requires some Search Engine foo as the full class name is missing in the MSDN documentation.

Once you have PowerPoint open, you need to open the presentation and just save it as PDF. This is also easy, although you have to use the right enum (the string ‘pdf’ is not adequate):

$pres = $ppt.Presentations.Open($ifile)
$opt= [Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType]::ppSaveAsPDF
$pres.SaveAs($ofile,$opt)

In addition to the code here, you also need to clean up and close PowerPoint. You can see how to do that in the script on the PowerShell scripts blog

To test it, I ran this script (which is part of the script posted on the scripts blog!).

$ipath = "E:\SkyDrive\PowerShell V3 Geek Week\"

Foreach ($ifile in $(ls $ipath -Filter "*.pptx")) {
  # Build name of output file
  $pathname = split-path $ifile
  $filename = split-path $ifile -leaf
  $file     = $filename.split(".")[0]
  $ofile    = $pathname + $file + ".pdf"

  # Convert _this_ file to PDF
   Convert-PptxToPDF -ifile $ifile -OFile $ofile
}

So all things considered, it was relatively easy to create a script to do this conversion. And as this sort of thing is something I do all too often, this script will save me time in the future!

Technorati Tags:

Thursday, October 04, 2012

So You Need a Further Excuse to Book Onto The Next PowerCamp? DONE!

The next PowerShell PowerCamp event is coming up shortly and we’re rapidly selling out of places. The PowerCamp event is two fast-paced days looking at the basics of PowerShell V3 – I cover as much as I can over two days.

The PowerCamp event is primarily focused on those new to PowerShell but with plenty of depth for those with more skills. I’ve been running these for a couple of years and they are a lot of fun – both for me (I just LOVE talking about PowerShell – as any of my students will attest!!) and for the delegates who pick up a lot of useful skills and get to network with like-minded folk.

The next PowerCamp event, October 27-28 in London, is rapidly selling out – but if you are holding off, waiting for more reasons to book, you are in luck. Now to be honest, I think the two days of training is more than worth the fee, but I do try to add value and give you things to enjoy on the day and to take away.

So two important announcements:

First, those very nice people at Pluralsight are providing attendees with a free one-month trial membership to Pluralsight’s huge catalog of training material. Although Pluralsight is mainly a developer training company, there is a fair bit of cross over material – and I’ve published several PowerShell courses into their library already – and by the time PowerCamp rolls around, there will be an additional course, My Top-10 Coolest Features of PowerShell V3 with Windows 2012.

Second, those other very nice people at MVP Systems, attendees will get a nicer than normal Costa gift card for coffee – there’s a Costa Shop right outside the building where we are meeting. The PowerCamp event is being held in Microsoft’s Cardinal Place offices – and over the weekend there is no catering on site – but armed with your gift card, you can be sufficiently caffeinated! At least that’s the plan.

In addition to some truly great training (I had to say that!), some free coffee and a month’s free subscription to PluralSight, there will also be the traditional give-away memory stick with all the great PowerShell related goodies I can find and provide. And while I can’t announce anything yet, I am still working on a couple of more goodies for you to take away.

So if you want to learn more about PowerShell v3, AND get some cool goodies, sign up now – see http://tfl09.blogspot.co.uk/2012/08/announcing-powershell-v3.html for details on how to book. I hope to see you there!

 

Sunday, September 30, 2012

PowerShell v3 for Down-level OSs

As most of you probably know, the latest version of PowerShell, PowerShell v3, shipped inside Windows 8 and Server 2012 (including Server Core!). Microsoft has also released versions of PowerShell v3 for older versions of windows. Specifically, you can now download PowerShell v3 for:

  • Windows 7 – both 32-bit and 64-bit. You must have at Win7 SP1 loaded. (64-bit – 15.8MB, 32-bit 11.7MB))
  • Windows Server 2008 - both 32-bit and 64-bit. You must have at Server 2008 SP2 loaded . (64-bit - 14.4MB, 32-bit 10.5MB))
  • Windows Server 2008 R2 - 64-bit only and includes Server Core. You must have at Server 2008 R2 SP1 loaded 15.8MB)

If you’ve been running a beta version of PowerShell v3, then you have to remove it first before installing v3.

To get the various installation packages for your system, go to http://go.microsoft.com/fwlink/?LinkId=251995 (the Microsoft Download Centre) and look for Windows Management Framework 3.0. This package has PowerShell V3, and all the necessary plumbing (latest version of WSMan, some new cmdlets, etc, etc, etc.).

If you need to remove the WMF 3.0 package, you need to look for the KB article (KB2506143 for Windows 7 SP1 and Windows Server 2008 R2 SP1; KB2506146 - for Windows Server 2008 SP2)

There’s no excuse – get the latest version today!

Technorati Tags:

Thursday, September 27, 2012

Updated Start8 From StarDock

I see from email that StarDock has released an updated (beta) version of their Start8 utility that I wrote about recently. This neat little app puts the Start button back into Windows, meaning it’s easier to use (at least for some!).

When I last wrote about it, I got a lot of comments – as expected. Some of the comments, received in mail, on the blog and via twitter, were along the lines of ‘Windows 8 is different, get over it and learn it’  - something I can’t really rebut!  But I also got quite a lot of agreement as well as lots of cool tips on how to improve one’s experience with the Windows 8 UI. For all those comments, thanks.

It’s true that I can live without the start button and by using a combination of new keyboard sequences and pinning what I need to the desktop’s task bar (and ignoring the Start Screen) I can get by. BUT: why should I have to go to all that effort? If Microsoft had listened to folks like me, they would have given me the freedom and the opportunity to choose. It would have cost them nothing to have left the start button in the UI (if anything, ripping it out probably cost Msft more in engineering and testing than leaving it in would have cost). And it would have made the Windows team seem a bit less arrogant. But they didn’t and so I’m left with dealing with that. But anyway – if you are missing your start button – Start8 is a way to reclaim it. I like it and it, for me, makes Windows 8 a whole lot more attractive AND it makes me more productive.

One small thing – although in beta, Stardock have started charging for it. From their web site, the cost is US$4.99 or around £3.33. This is a sufficiently cheap price that I said yes in a flash.

And two final things: If you DO buy Start8, and want to save 10%, cite this discount code: RC-00017391. Second, thanks to John J Kavanagh, there’s an open source project that does much of what Start8 does – see http://http://classicshell.sourceforge.net/

Friday, September 21, 2012

Even More about Windows Server Core 2012 and GUIs

I’ve written a bit recently about Server Core in Server 2012. But here’s yet more details. In Server 2012, the GUI is an installable feature – one you can add or remove. There are actually three levels of GUI within Server 2012:
  • Full GUI – the full blown Windows Server GUI as we’ve always known it plus the Metro start panel, etc.
  • MinShell – a partial GUI but one that enables you to run things like Server Manager, some control panel applets,MMC consoles and PowerShell ISE.  But no desktop/Metro Shell and no IE.
  • None – The server core GUI as we love it – but with the opportunity to specify PowerShell as the window to open at boot (or when you RDP into it).
This provides a great compromise – you can have the GUI where you need it and remove it when you don’t. I love that – although not all applications will run on MinShell or Server Core itself. You need to check – but increasingly applications are server core friendly! For both MinShell and Server Core, the default is to run CMD.EXE as the default shell – when you logon to a server core box you see CMD.Exe. You can fix that easily enough so that at boot time you get PowerShell instead – a simple registry fix.
As part of the Launch of Server 2012 here in the UK next week, I’ll be presenting a bit on PowerShell and showing some of what it can do. One aspect of the server we are showing is Server Core and I’ll be demoing how easy it is – I wrote a script for that:
Function Set-GUI {  
[Cmdletbinding()]
Param(
[ValidateSet("Full", "MinShell", "None")]
[String] $GuiType = "Full"
)
# Here check what to do and do it Switch ($GuiType) { "Full"     { Add-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra
             $RegPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon"
             Remove-ItemProperty -Path $RegPath -Name Shell -ErrorAction SilentlyContinue –Force
           }
"MinShell" { Uninstall-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra  # Just in case
             Add-WindowsFeature Server-Gui-Shell
             $RegPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon"
             Set-ItemProperty -Path $RegPath -Name Shell -Value 'PowerShell.exe -noExit -Command "$psversiontable"'  -Force 
           }
"None"     { Uninstall-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra
             $RegPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon" 
             Set-ItemProperty -Path $RegPath -Name Shell -Value 'PowerShell.exe -noExit -Command "$psversiontable"'  -Force  }
Default    {"$GuiType unknown - enter Full, MinShell or None"; return
           }
}
# Finally Reboot into new gui mode!
Restart-Computer
} # end of Set-GUI function
This could usefully have been added into the ServerCore Module!

Tuesday, September 18, 2012

Adding Keyboards in Server 2012 (and Windows 8)

In Server 2008 R2, you could use a control panel applet to add a new keyboard layout to your system – and for those of you whose normal UI-culture is other then EN-US, this is very useful. I have a very nice Microsoft Natural keyboard with a US layout. If I install an OS with En-Us, then I get the American keyboard just fine. Sadly, this means I can’t easily get to the £ and € characters. So I install a US-EN operating system, then use control panel to add a language (EN-GB) and then I have a nice task bar menu to enable me to select the one I want. As I touch type, moving between one keyboard layout and the other is pretty easy once I have both layouts loaded.

The only thing – Microsoft moved the place to configure my extra keyboard between Server 2008 R2 and Server 2012. In Server 2008 R2 (and Win 7), you use Control Panel and selecting Change keyboards or other input methods.

 

 image

 

This bring up the Region and Language dialog box, from which you click on Change Keyboards

image

 

This in turn brings up the Text Services and Input Languages dialog box. From here you click add to add a keyboard. The screen shot here is from a Server 2008 R2 computer with both US and UK keyboards loaded.

image

 

However, in Server 2012, Microsoft’s changed control panel and place where you add new keyboards. From Control Panel, you now select Add a language:

 

image

This brings up the Language Dialog box from which you can Add a language. The below screen shot is from a Windows 8 box with both keyboards loaded.  

 

image

So why did they change it? No idea – I suppose mainly because they could. But now you know where they hid that!

More on PowerShell on Server Core

PowerShell and Server Core – Server 2008 R2 and 2012

in July, I wrote a few articles on PowerShell in Server core (here, here, and here). There were two key points noted in those articles. First, Server Core in Server 2012 has a removable GUI – you can add it or remove it! Secondly, in Server Core in Server 2012, by default, the system starts up running CMD.EXE, not PowerShell, although there’s a simple registry hack that enables you to run PowerShell instead.I’ve been playing with this a bit and have discovered a few additional things about Server Core and PowerShell.

Adding PowerShell v3 to Server 2008 R2 Server Core

The first interesting thing I’ve found is that you can add PowerShell V3 to Server 2008 R2 Server Core. However, to do that, you need to add the .NET Framework 4.0 to your server core system. Go to the Microsoft Download centre and download the Microsoft .NET Framework 4 (Standalone Installer for Server Core. Your Server Core installation needs to be running SP1 or higher. Read the instructions carefully!

Adding GUI to Server Core – Which Shell to Run

In one recent article, I noted how you could add and remove the GUI from Server Core. I’ve written two functions (Enable-GUI and Disable-GUI) that convert between the two GUI modes. I’ve tested these functions pretty thoroughly and the adding and removing of the GUI is straightforward, albeit on the slow side.

One thing I found is that if I first set PowerShell as the default shell (see here), then add the GUI, when Windows Server 2012 restarts, you have the GUI, but the shell itself doesn’t start – PowerShell runs as the default shell!  It took me a few minutes to work out what was going on. A very simple workaround is to remove the Shell default value from the Registry before rebooting. The code to add the full GUI back to Server core now looks like this:

Install-WindowsFeature Server-Gui-Shell, Server-Gui-Mgmt-Infra -Source d:\sources\sxs
$RegPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\winlogon"
Remove-ItemProperty -Confirm -Path $RegPath -Name Shell -ErrorAction SilentlyContinue

To get the full scripts see here (for Enable-GUI) and here (Disable-GUI).

Sunday, September 09, 2012

PowerShell PowerCamp October 27-28th–Filling up and a Special Guest!

Now that folks are back to work and catching up on their reading, I’m starting to get bookings for the October PowerShell PowerCamp event (http://tfl09.blogspot.co.uk/2012/08/announcing-powershell-v3.html for the details). It’s great to get mail from folks asking for a place – so far the farthest away is from New York City. Very Cool!

As those who have come on earlier events know, I try to have an extra guest to come along and offer some additional thoughts on how to best use PowerShell. I give them leeway to talk about whatever they want – past events have seen James O’Neil and Tom Arbuthnot provide some thought provoking insights. In October, I’m very pleased to announce that we’ll have Richard Siddaway. Richard is a well published PowerShell author and an MVP.

So if you are looking for a fast paced, fun filled introduction to PowerShell, this is an event for you. I hope to see you there to continue your journey into the joys and delights of Windows PowerShell v3.

Saturday, September 01, 2012

Start8 – Get the Start Button On Windows 8

Like many users of Windows 8, I really dislike what some call its bi-polar User Interface – the appalling (IMHO) start screen combined with the partially neutered desktop. And don’t get me started on how lame I think most of the Metro (SIC) applications are? We had a better UI than this in Windows 2! Why can’t I just overlap Metro (SIC) apps? Why can’t I have 3, 4 or more all up on the screen at once?  The same sentiment occurs on Server 2012, although on Server 2012, I’m well served with PowerShell!

Despite all the other goodness that is inside Windows 8, I find this UI poor. It really makes me dislike Windows 8, and (to use the language of all the Msft surveys I seem to get!), it does not make me feel better about Microsoft. Now, I am sure that a) many people love this new UI and b) it will be great on a tablet or phone. But for me, this dual-purpose UI is just plain a waste of space on corporate desktop PCs that, by and large,  continue to be used by knowledge workers using desktop applications – even Office vNext is not a Metro app (well not yet anyway). 

I have two great big 24-inch TFT panels that are not touch sensitive. Initially, using both Windows 8 betas and Server 2012 betas, I found myself constantly flipping back and forth between the desktop and the start screen. This was slow and very painful – and made me put Windows 7 back onto one of my desktop machines.  From the press coverage of Windows 8, I know I’m not alone! Although public opinion is not totally on my side, it’s pretty heavily weighed that way! All in all, Microsoft could have, and should have, done better.

Imagine my delight and excitement when I came across Start8, a new application from StarDock. Simply put: this application puts the start button back into Windows 8. It also changes the startup process so that instead of dropping you onto the Metro (SIC) Start screen at boot time, you are put straight into the Desktop. And there’s even a ‘start/run’ box on the Start menu! This is what, IMHO, Windows 8 really should have looked like: It lets me use Metro and Metro apps when that is appropriate (maybe if I get a Surface), but not have the start screen in my face quite so much. And on desktops and laptops, I get the best out of Windows 8 using a familiar and easier to use UI! I have converted my laptop to Windows 8 and with Stat8, I am enjoying the new OS.

Here’s what it looks like in one of my Windows 8 VMs.

image

 

Notice the nice shiny start button just where it used to be?  Well – when you click it, you see:

image

 

 

And as a really cool added feature, if you right click that button, you get to shut down the system – which looks like this:

image

Now, with the start screen (and the metro apps that come with it) are not so in my face, all that awful stuff I hated about Win8 is now largely a memory. On my main Win8 box (my laptop!), I’ve installed my favorite browser and music player, and now spend almost all my time on the desktop using desktop applications. And being productive!

For me, this has transformed my view of Windows 8. Instead of fighting the UI every time I try to use it, I now can be productive, and enjoy all the truly great features of Windows 8. With Start8. I now really enjoy using Windows 8. I have even recommended it to some of my friends working at a large software giant who agree with my views on the UI (even if they probably can’t be seen being productive and using it).

Right now, whilst it’s in beta, Start8 is free. But I like it sufficiently, I’m happy to buy it when it is finally released. This product makes Win8 usable for me and as long as Microsoft feel they know better about what my PC should look like, it’s going to stay on my Windows 8 and Server 2012 desktops.

My overriding question is: if an ISV like Stardock could do this and make it look so good, why couldn’t Microsoft?

Saturday, August 25, 2012

Announcing PowerShell V3 PowerCamp – October 27/28 2012 in London

Now that the summer is (nearly) over, it’s time to get back to what mattes. With the imminent arrival of both Server 2012 and Windows 8 to general availability, learning PowerShell is now, more than ever, something every IT Pro needs to do! One great way to get up to speed is via my PowerShell PowerCamp events!

What is A PowerShell PowerCamp?
PowerCamp is a fast paced weekend training event that covers all the basic aspects of Windows PowerShell v3 - from the command line to writing production-oriented scripts. We start with the basics including configuration, formatting and providers and remoting and jobs. Then, on day 2, we look at scripting, work flows, managing script libraries using modules, WMI/CIM,  using objects, and finishing with the PowerShell features added into Windows. The event concludes with a short look at PowerShell in the cloud and a quick call out to all the things we just can’t cover in two days.

The PowerCamp event is a combination of lecture, demonstrations plus Q&A, with the opportunity to type along with the tutor. There are no formal labs. But I do provide the key demos, all the slides, plus a wealth of other add on material on a memory stick you get at the start of day 1. So bring along your laptop, and type away.

What is the Agenda?
Day 1 – The Basics
• PowerShell Fundamentals – starting with the key elements of PowerShell (Cmdlets, Objects and the Pipeline) plus installation, setup, and profiles
• What’s new in v3 – this looks at the things specifically added into PowerShell v3.
• Formatting – how to format output nicely – both by default and using hash tables and display XML
• Providers – getting into underlying OS data stores (certificate store, AD, registry, etc.) via providers
• Remoting and jobs– working with jobs plus working with remote systems using PowerShell’s remoting capabilities

Day 2 – Diving Deeper
• Scripting Concepts – automating everyday tasks including PowerShell’s language constructs, error handling and debugging and workflows
• Modules – managing PowerShell script libraries in the enterprise
• WMI and CIM – we look at the WMI and CIM components, including the new CIM cmdlets
• Using .NET and COM Objects – working with native objects
• PowerShell in Windows 2012 and Windows 8 – a look at what’s there and how you can leverage the huge number of new cmdlets
• PowerShell and the cloud – this module looks at PowerShell in the cloud and how you can use PowerShell to manage cloud computing.

What does it cost?
The cost is £200 (+VAT at the prevailing rate) for the weekend. Meals and accommodation are not covered.

Where is the event going to take place?
The PowerShell PowerCamp is being held at Microsoft Cardinal Place, 100 Victoria Street in Victoria on the weekend of October 27/28 2012. Each day starts promptly at 09:00 and finishes up by 16:45. We’ll also take short break throughout the day, including a 1-hour lunch break

PowerDrinks?
After Saturday’s session, attendees are invited to a small nearby public house for some lovely English ale, etc.

Who is the tutor?
The PowerShell Weekend PowerCamp is delivered by Thomas Lee. Thomas is a veteran PowerShell MVP who has been involved in the PowerShell community since the very beginning. He provides training and consultancy around a range of Microsoft products, with a recent focus on PowerShell and Lync Server. Thomas runs PowerShell training courses around the world, and has been a speaker at conferences across the world for the past decade. In his spare time, he lives with his wife, daughter, wine cellar, and Grateful Dead live recordings archive in a small cottage in the English countryside. His Twitter handle is @DoctorDNS and he maintains two blogs (Under the Stairs at http://tfl09.blogspot.com and PowerShell Scripts Blog at http://pshscripts.blogspot.com).

What do I need to bring
You need to bring a laptop with PowerShell v3 loaded. That can be either native or in a virtual machine. I suggest you have at least two VMs pre-configured – one a server 2012 installation the other a Windows 8 installation. The virtualisation software is not of concern – but you need 64-bit guest OS support for Server 2012! Thus you can use Hyper-V, VMware Workstation or Oracle’s Virtual Box. Heck, run it in a VM on a Mac or Linux PC if you want. Just bring along PowerShell v3!

 
How do I book?
Contact DoctorDNS@Gmail.com to book a place and to arrange for the invoice to be paid. Payment must be in cash, cheque or bank transfer – I don’t take credit cards.

More Details
Watch this blog for any hot breaking news on the event.

 

Taming Wild Console Applications in PowerShell v3

One of the great features of PowerShell, especially for beginners, is that you can easily run old console applications that were originally written to be run under CMD.EXE. These are can be managed or unmanaged applications as well as older VBScripts. PowerShell, and PowerShell v3, just runs them. However, there is a fundamental problem which can often trip up those new to PowerShell (and from time to time us oldies too!).

In PowerShell there is a single parser therefore a single syntax that each and every cmdlet, function, script object, etc., have to obey. There’s only one parser, therefore there’s only one way to call a script/function/workflow/etc. This consistency is is wonderful. Compare that to older console line applications where each application implements it’s own parser, implementing an application unique syntax for usage. Compare NetShell, with it’s hierarchical contexts with calling IPconfig that uses the ‘/’ character to prefix parameters.

For the most part, the syntax you use when running a console application in CMD.EXE is the very same as you would run in PowerShell. So that’s all good then. Well – there are exceptions. There are some console applications whose command syntax confuses PowerShell’s parser. That is, the way PowerShell’s parser parses the call to that application does not quite do what you want. My favorite example is BcdEdit.exe. According to TechNet, you can use BcdEdit to add a native-boot VHD to an existing WIn7 boot menu (and appears to work just fine for Win8 too!) using the following commands:

bcdedit /copy {default} /d "vhd boot (locate)"
bcdedit /set {guid} device vhd=[locate]\windows7.vhd
bcdedit /set {guid} osdevice vhd=[locate]\windows7.vhd
The problem here is that BcdEdit wants arguments that are enclosed in brace characters – PowerShell sees text inside a pair of braces as a script block, not just a string that happens to have a pair of brace characters at the start/end. The result is that the command will not do what you want. There are often discussions on various PowerShell Forums. The solution rationally was to add quote characters, e.g.:
bcdedit /set “{guid}” osdevice vhd=[locate]\windows7.vhd
Which works, but is not always obvious. There are other examples which are even harder to fix quickly. The problem this causes is that it ‘proves’ to those who want it to, that PowerShell is not quite ready. The reality is that moving from one older inconsistent regime to another hopefully consistent regime was bound to turn up a a few minor incompatibilities. These areas are ones that came in for a lot of attention in PowerShell v3.
For those facing this issue, one of the cooler features in PowerShell v3 is the –% operator (that is: two hyphens and a percent symbol). You specify this character sequence after the command name but before the command’s parameters, like this.
bcdedit –% /set {guid} osdevice vhd=[locate]\windows7.vhd
What this character sequence does it to tell PowerShell to just pass the rest of the command line to the console application ‘as is’. This means you can old .bat scripts into .ps1 scripts, incorporating new PowerShell features for example, but being able to convert the calls to some curiously written console applications. 

Wednesday, August 22, 2012

My First Windows 8 Bug–PowerShell to the Rescue

Unless you are living in a cave, high in the Himalaya, you must have heard that Windows 8 made it to release. After a long wait, it was finally made available on TechNet – and I downloaded it as quickly as I could. My first action for any new OS build these days is to fire it up in a VM and see what’s there, which I duly did. The Installation process, which we first saw with Vista, is quick and my VM was ready in a flash. Since this is a VM I plan to keep and use, I went to activate it.

To activate Windows 8, you bring up the PC Settings:

image

Clicking Activate brings  up this message:

image

 

Bringing up the Action Center/Windows Activation, and I get this error screen:

 

image

Notice the red squared items. It shows a partial key (no idea where it got that from as I never entered one!). And it shows an Activation Error – DNS name does not exist. WHAT?  On the assumption that this error message was vaguely right, I spent some time trying to see what DNS issues there might be – needless to say I found nothing obvious. I moved the VM around, changed VM networking, etc. but to no avail.

I then spent some more time trying to work out how to add the correct key. I assumed that a) the error was nothing to do with DNS, and b) the real error was invalid key. But there seems to be no way, in this ‘fast/fluid’ dialog box, to add a key. I never was able to work out how to do that from the GUI, and the built in help text referred to dialog boxes that did not appear to exist.

Just as I was about to give up and turn to TechNet forums for help, I remembered a trick I used to use in some MOC Classroom setups where I continually had licensing problems. Naturally, these days, the solutions is almost always PowerShell based or at least invoked from PowerShell!

So after firing up PowerShell, in an elevated prompt, I ran the SLMGR.VBS utility, which brings up several pages of help text. On the first page I saw this (NB: if you click OK on the first page, the script brings another page of help text, and another  – there are several!).

Here’s what I see on the first page:

 

image

 

So,in the elevated PowerShell prompt, I just entered two quick commands as shown below. Of course, my key is not really FFFFF-EEEEE-etc., but you get the idea.

image

After typing 'slmgr –ipk <key>’, I get the following dialog box (which shows the real key I entered – but I’ve blacked that out for the purposes of this blog post):

image

After entering a key, successfully, I just entered ‘slmgr /ato’ to bring up this (also masking out my real key):

image

 

So once again, PowerShell to the rescue of the ‘fast/fluid/fail’ that seems, to me, to sum up Windows 8.  Thinking about it, this is the sort of problem you see in  a product that was not well enough tested (aka rushed out before it’s ready). Why wasn’t this tested fully and this bug found and fixed? And a second question – why do I need to use VBScript? Has the Windows activation team not heard of PowerShell?

I suppose all’s well that ends well – my VM is activated and I know how to do it again when I need to. But it leaves me with an unpleasant feeling – if something so fundamental as activation is broken, what else is? I guess we’ll find out soon enough.

[Later]

I wrote the outline of this blog post last night and did most of the screen shots and posted it this morning. After doing so, I see from my mail box that I am not the only person to have found this bug (and solved it). Having said that, I think I’m the only person who used PowerShell!  So apologies if you beat me to it!

Friday, August 17, 2012

PowerShell Version 3 – Help Soon Coming

As I blogged in March, PowerShell V3 comes with Updatable help. This is a fantastic new feature that allows for Microsoft, and any PowerShell module maker, to create updated help for the code in their modules. Thus errors can get fixed in the in-box help. The implementation Microsoft chose is not perfect – there is only minimal help ‘in the box’. You have to use Update-Help in order to get the help contents. I regard this as a bug, but Microsoft describe it as a feature. Irrespective, I do like this feature!

Now that Windows 8 is released, so is PowerShell V3. Sadly, not all the help text has been released. Given the thousands of new cmdlets that ship with V3 and Server 2012, this is not surprising. While it would have been nice to think that help text is a sufficiently important part of the product to complete before RTM – that wasn’t the way it was done. So in order to get help in PowerShell V3, you will need to continue to use Update-Help. Once all the help text is available, I’ll try to post again!

One artifact of this situation is that Update-Help generates a couple of errors. Today, if you try to update help, you may see the following error:

Update-Help : Failed to update Help for the module(s) 'CimCmdlets' with UI culture(s) {en-US} : For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
At line:1 char:1
+ Update-Help -force -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Update-Help], Exception
    + FullyQualifiedErrorId : HelpInfoXmlValidationFailure,Microsoft.PowerShell.Commands.UpdateHelpCommand

The problem here is that the CimCmdlets (and possibly other modules) point off to Microsoft’s web site where Update-Help is meant to be able to find the updated help for this module (or modules). Sadly, the pointer from the module points to a nonexistent page, which Microsoft helpfully points off to Bing. That’s great for most things, but Update-Help gets the Bing page, which it tries to read as XML which is not quite right.

This is sad, but PowerShell updated help is still a work in progress – and given the magnitude of the task, I suppose the PowerShell Team can be forgiven. I must say, a LOT of modules have been updated over the past few days, and I would expect all the help text to be complete well before General Availability of Windows 8 and Server 2012.

Bottom line: Updatable help rocks, but we need just a bit of patience till it’s all here!

 

Monday, August 13, 2012

PowerShell Version 3 is RTM!

A few days ago, Microsoft announced that Windows 8 ( on August 1st according to Wikipedia). A key component of Windows 8 was the final release of Windows PowerShell version 3. Unfortunately, you (and i) can’t quite get it yet!

PowerShell V3 is going to come out in two ways:

  • In the box – when you get the RTM version of Windows 8 and Server 2012, you’ll get V3. Although you can run version 2 side by side, this does not work on initial installation – you need to install .NET v2.
  • Down-level Operating Systems – an updated version of the Windows Management Framework will ship sometime soon that contains all the necessary bits you need to run PowerShell v3 for down-level OSs. My understanding is that this will ONLY be supported on Server 2008, Server 2008 R2 and Windows 7 (i.e. no Vista).

Starting in a couple of days, customers will be able to download Windows 8 and Server 2012 and will have v3 in the box. The WMF update for down-level OSs will come some time after that.

Once the release is in my hands, I’ll be able to blog about all the cool features that are in v3!

Technorati Tags: