Friday, November 28, 2014

Microsoft is developing the Azure PowerShell tools (and for that matter all of Azure) in an agile way – delivering frequent incremental changes and new features. Keeping up is, to say the least, non-trivial. One way to keep up with the PowerShell tools is to look at the ChangeLog.Txt file on the Azure SDK tools site on GitHub. That page lists, at a high level, the changes implemented in each new version of the tools.

As an indication of how fast Azure, and the PowerShell tools are evolving there has been over a dozen updates this year – roughly one a month, with some months more. That is a very fast pace of development.

I've had two blogs on BlogSpot (both before and after the take over by Google!): this blog (aka Under The Stairs) and a PowerShell Script blog. Until recently, the format of these two blogs has been pretty static. But promoted by a couple of comments, I've updated the layout of both blogs. Both blogs are now a bit wider and both use new templates.

An issue with the PowerShell scripts blog is that the formatter I was using also used an online CSS. Sadly, both the site and the CSS object are gone – more Internet goodness that is impermanent. I have switched over to a new formatter, but it's going to take some time to get around to fixing all of the post. I've done a few, but there are around 300 more to do! Eventually!

I'd be happy to get comments about the blog. Has anyone actually noticed?

Thursday, November 27, 2014

When a PowerShell script runs, it can create a number of different types of output, including success output, errors, warning messages, verbose output, and debug messages. By default, each of these streams of output are merged to the console host when your script runs. This usually makes sense, but some times, you may want to capture the different streams of output separately.

Simon Wahlin has published an interesting article that shows you how you can combine the redirect operator (">") and the stream number to achieve that. This is great information about a somewhat obscure feature. The technique involves combining the re-direct operator with the stream number based on:

Stream

Stream Number

All Output

*

Success output

1

Error output

2

Warning messages

3

Verbose output

4

Debug output

5

Then you follow the command you want to capture on, the stream number, redirect operator and where you want the output to go. Simon has a simple function that creates each type of output (Write-ToStreams). If you want to capture the output of, say, the verbose stream, you'd run the function like this:

Write-ToStreams 4>4out.txt

And if you wanted to send the verbose output one way, and the error output another, you could achieve it like this:

Wednesday, November 26, 2014

With the latest version of Windows Server, you can now create a new type of Virtual Machine – A generation 2 VM. These VMs now suppport a number of new features, but require a new format of disk drive. You might have thought that it would be very simple: just do a New-VHD and specify a –Generation 2 parameter. If only it were that simple.

I've struggled with working out how to do this and have not found much help out on wider interweb. Until I came across a great post from Jeff Hicks, Creating a Generation 2 Disk with PowerShell. In this post he goes over the steps required to make a Generation 2 disk – which is actually not all that easy. Unfortunately, the whole job is not doable via PowerShell cmdlets – you need to cheat a bit and use diskpart.exe. But once you know how, you can hide the details inside a function and just use that function going forward.

I am working on updating my scripts to build out my training course test lab based on Windows 10 server. I will be moving over to Gen 2 VMs (and VHDs), so this article is especially important to me!

Tuesday, November 25, 2014

In a previous article, I set out what a class was and what it contains, and showed examples of using those classes in your PowerShell scripts. As I mentioned last time, you should use cmdlets where possible to create and manage objects. But when you can't you can always delve into the .NET Class Framework and it's huge class library.
But what if there are no applicable .NET objects and you need to create your own class? Some admins might be asking: why bother? The answer is one of flexibility and reuse. If you are writing scripts to automate your day to day operations, you are inevitably passing objects between scripts, functions, cmdlets. There are always going to be cases where you'd like to create your own object simple as a means of transporting sets of data between hosts/scripts/etc.
In PowerShell V5, Microsoft has included the ability to create your own classes. When I started writing this set of articles, I had initially intended to just introduce Classes in V5, but as I looked at it, you can already create your own objects using earlier versions of PowerShell. These are not fully fledged classes, but are more than adequate when you just want to create a simple object to pass between your scripts/functions.Creating Customised Objects
There are several ways you can achieve this. The first, but possibly hardest for the IT pro: use Visual Studio, author your classes in C# then compile them into a DLL. Then in PowerShell, you use Add-Type to add the classes to your PowerShell environment. The fuller details of this, and how to speed up loading by using Ngen.Exe are outside the scope of this blog post. Bringing C# Into PowerShell
Now for the semi-developer audience amongst you, there's a kind of halfway house. In my experience, IT pros typically want what I call data-only classes. That is a class that just holds data and can be exchanged between scripts. For such cases, there's a simple way to create your class, although It does require a bit of C# knowledge (and some trial and error).
Here's a simple example of how to so this:

This code fragment defines a very small class – one with just 4 members (Model, number in fleet, range, and max number of passengers). Once you run this, you can create objects of the type AeroPlane, like this:
As you can see from the screen shot, you can create a new instance of the class by using New-Object and selecting your newly created class.
If you are just creating a data-only class – one that you might pass from a lower level working function or script to some higher level bit of code – then this method works acceptably. Of course, you have to be quite careful with C# syntax. Little things like capitalising the token Namespace or String will create what I can only term unhelpful error messages. Using Select-Object and Hash Tables
Another way to create a custom object is to use Select-Object. Usually, Select object is used to subset an occurrence – to just select a few properties from an object in order to reduce the amount of data that is to be transferred. In some cases, this may be good enough and would look like this:

Note that when you use Select-Object like this, the object's type name changes. In this case, the dir (Get-ChildItem) cmdlet was run against the File Store provider and yielded objects of the type: System.Io.FileInfo. The Select-Object, however, changes the type name to SELECTED.System.IO.FileInfo (emphasis here is mine). This usually is no big deal, but it might affect formatting in some cases.
But you can also specify a hash table with the select object to create new properties, like this:

As you can see form this code snippet, you can use Select-object to create subset objects and can extend the object using a hash table. One issue with this approach is that the member type for the selected properties (the ones included from the original object and those added) become NoteProperties, and not String, or Int, etc. In most cases, IT Pros will find this good enough.
In the next instalment in this series, I will be looking at using New-Object to create a bare bones new object and then adding members to it by using the Add-Member cmdlet and how to change the generated type name to be more format-friendly.

The provider is used to configure the SMBIOS on Dell's 'BizClient' systems. It was originally build for PowerShell V3, but I've installed and am using it on Windows 8.1 and PowerShell V5 November Preview. Before you can use the module you need to install Dells HAPI driver (provided in module download noted above. See the release notes for specifics, but installing the driver is painless - done by unzipping the files, then running HAPIInstall.exe. I created a sub folder and extracted the files into the sub folder before running the installation, which looks like this:

This screen shot comes from my Latitude E6520 laptop. Once the driver has installed, you can then access and use the module. Typing Get-BiosSettings, brings up a sweet grid view containing all the current bios settings, something like this:

The provider itself is also pretty cool – you can use the CD/LS commands to view various items as well as set their values. For example, you could change the Bios Setup Admin password, or whether numlock should be turned on at boot, etc. As with most providers , you can easily retrieve information from Dell's provider that would be helpful for troubleshooting as well as for reporting. You can also use the provider to change BIOS settings. Using the provider is easy and looks like this:

This module should work on most of the Dell range, although I have not tested it extensively. One neat looking feature is the ability to remove the bios setup password.

Saturday, November 22, 2014

Over the years in the industry, I've had the opportunity to use pre-release software. Some of it has been pretty awful, while others perfect or nearly so – and more in between. Using software that has not been richly tested is always a bit of a gamble, although some vendors are better than others. Of course, issues during pre-release typically get resolved prior to general release – so these errors really only affect those of us mad enough to use beta code!

With that in mind, I downloaded the latest build of PowerShell V5 as soon as it was released. I was anxious to see what, if anything, had become of the Chocolatey provider for Find-Package (OneGet) as it had been removed in an earlier beta version (as previously noted!). So my first test was to do both Get-Module and Get-Package to see the two 'get' package managers in action.

Much to my surprise, running Find-Module produced a ton of errors:

Weird, to say the least. I tried to see if other beta testers were seeing this issue the ones I was able to chat with did not see this error. Then I was having a Skype conversation with Aleksander Nikolic who asked me what culture I was using. As you can see in the above screen shot, I'm using my home culture (en-GB). He suggested it was culture related. To test this, I spun up an Azure VM, loaded the new version of PowerShell V5 and, as if by magic:

Just as I expected! This looks to be another culture issue – one that will no doubt be sorted out by the time RTM comes around (or, hopefully, a newer build is released that works with En-GB).

It's easy to understand this issue, but I guess I'd have been less surprised and frankly less disappointed, if the issue had been mentioned in the otherwise excellent release notes (or possibly even acknowledged in the release notes). One for the future perhaps.

Wednesday, November 19, 2014

Microsoft has just released a updated build of PowerShell V5. I am particularly excited at the sheer pace of progress that is in evidence. Many features, particularly Desired State Configuration, are unfinished – works in progress. But what progress is being made!

Tuesday, November 18, 2014

A possibly obscure blog post title, but please read on. In PowerShell V5, Microsoft includes two cool modules: PowerShellGet and OneGet. PowerShell get is meant to find and manage PowerShell modules while OneGet is meant to find and manage 'packages'. This allows you to search for, download and install a substantial library of software and a library of PowerShell modules. This is a great way to leverage the community!

In the first drop of PowerShell V5, Get-Package got it's list of packages, inter alia, from Chocolatey a Windows friendly package provider. But unfortunately, the link to Chocolatey was removed in the latest V5 drop. I'm not sure why, although I'm sure there is a sensible explanation. And after all, this is a work in progress. But no matter why it's gone – I want it back. Turns out it's pretty easy to do that.

To setup Chocolatey as a package provider in the latest V5 drop, it's easy:

Life is so simple when you know how! And once you do that, Find-Package returns a LOT more packages. SO happy hunting.

I am looking forward to more clarity around the differences between OneGet and PowerShellGet, particularly in how Enterprises are meant to make use of them. I can see several approaches that could be taken and hope to see more information as we progress towards the release of PowerShell V5.

Wednesday, November 12, 2014

Microsoft has this week announced that it is providing the full .NET Server stack into Open Source. This includes ASP.NET, the .NET compiler, the .NET Core Runtime including the Framework and Libraries. This Microsoft says this should enable "developers to build with .NET across Windows, Mac or Linux". For the details, see http://go.microsoft.com/fwlink/?LinkId=518340.

And as if that were not enough Open Source goodness, Microsoft also announced Visual Studio Community 2013 – a free, fully featured version of Visual Studio including full extensibility. Developers, or anyone else interested, can get started with Visual Studio Community 2013 HERE.

Monday, November 10, 2014

As I noted in previous blog posts (here and here) one of the many cool features coming with PowerShell V5 is the ability to develop Classes and Enums using PowerShell. in Monday's blog post, I showed how you could create an Enum, one important construct useful to creating classes.

Before I look at creating classes with PowerShell V5, it might make sense to go over what a class is and what creating them means. Many PowerShell users may be under familiar with the concepts involved.

Classes

The first thing to cover is classes. But what IS a class? A class is the definition of an object. In PowerShell everything you do relates to instances of objects that belong to some class. If you issue Get-ChildItem on the file system provider, you get zero, one, or more object occurrences, or instances, of either the System.Io.DirectoryInfo or System.Io.FileInfo classes. The number 42 is an object of the class System.Int32,

The Class defines the object (and occurrences of that object). Each class has a number of members. These include constructors, properties, and methods. The constructor is how you create a new class instance (creating a System.Io.Fileinfo object (instance) pointing to c:\foo.bar.ps1). Properties are attributes of object are actions you can apply to the object, such as the name of a file. The properties and methods of a class can be either static (belonging to the class) or dynamic (belonging to a class instance). This is a difference new PowerShell – see below for more on the difference.

Constructors

A constructor is code that creates a new instance of the class. Constructors can take parameters that describe the object instance to be created. You can also overload constructors – creating more than one constructor with different sets of parameters. In the System.Net.Mail.MailMessage class, you can see 4 different constructors; one takes no parameters, while the other three take different sets of parameters, as you can see in MSDN. Each constructor creates an object instance (a mail message) but with different properties.

Properties

A properties is some attribute, either of the class itself or of an class instance. For example, the class [system.int32]. Each property has a type and this can be a value type (such as a string, or an integer) or a more complex object. An occurrence of the System.Net.Mail.MailMessage class, for example, has a simple Priority property that takes a string (Low, High, Normal). It also has a property, To, which takes an object of the class System.Net.Mail.MailAddresss. The point here is that an object instance (a mail message) has a property (to) that itself is an object which has properties (e.g. DisplayName). Of course, that property too could be an object etc etc (although in the case of System.Net.MailAddress it doesn't!).

Methods

A method is some function that the class is capable of performing – either on an specific instance (a dynamic or instance method) or based on the class (a static method). Dynamic methods usually do something to the instance, while static methods do something that relates to class itself. The System.Int32 class, for example, has both static and instance based methods. Individual instances of the the System.Int32 class contain methods that convert the instance's value to another form (e.g. Boolean, or System.Int64, etc). Those dynamic methods work on the the instance of the class. The ToString method on instances of System.Int32 converts the value into a nicely formatted string, with the help of a CultureInfo object, like this:

Static Methods and Static Properties

One concept that many new-to-PowerShell folks find harder to understand is concept of static (vs dynamic of instance) methods and properties. A static method is a method that does not make use of a specific instance of the class. Instead it works by doing something class related. The System.Int32 class has a neat static method, Parse. The Parse method takes a string and either parses that string into a 32-bit number or raises an exception if it can't correctly parse the string. The PowerShell Syntax to invoke a static method is: [<class name>]::methodname(<array of method parameters, or nothing>]. For example:

[System.Int32]::parse('42')

The System.Int32 class also has static properties or properties of the class. For example, MaxValue is the largest value that a System.Int32 can hold, while MinValue is the smallest value. In PowerShell, the Syntax for static properties is: [<class name>]::<propertyname>.

Here is an illustration of static methods and properties.

As you can see in this screen shot, the Parse method parses nicely the string '42' into a 32-bit integer. But the string ('4223452354234523452345235234'') could not be parsed and the Parse method threw an exception, the Overflow exception, as you can . You could use the Parse method inside a Try/Catch block to, for example, validate that some value passed in from a user is of the right form (i.e. a 32-bit integer) and catch and handle any exceptions to that validation.

A static property is some property related to the class not an instance. System.Int32 also also has some static properties, including MaxValue (the largest 32-bit integer), and MinValue (the smallest integer).

Creating Object Instances

PowerShell users typically create the object instance by using cmdlets (or functions, aka script cmdlets). Thus you use Get-ChildItem cmdlet and get instances of System.Io.FileInfo and/or System.Io.DirectoryInfo classes. In most cases, you process the objects instances by using cmdlets for example using Set-ADUser to update user information in Active Directory. Best practice says to use cmdlets where you can and only then drop down into lower level code.

There are three ways you can create new instances of an object (class). The first is via a cmdlet, but in the absence of cmdlets/functions, then you can either use a static method of the class or use the New-Object cmdlet and specify the class of which you wish to create an instance. One example is the class System.Guid, which it defines and manages guids. There are no cmdlets to manage this object type. If there had been, then you would most likely have a New-Guid cmdlet to create a new guid. Since that cmdlet does not exist, to create a new guid, you use a static method, like this:

.

The other way to create new instances is to use the New-Object cmdlet. This cmdlet uses the class constructors available and matches the parameters you specify with the various constructors. For example, you can create a new instance of the System.Mail.Mailmessage class using one of four constructors. To Create an empty mail message, you would do this:

In Windows, Microsoft and other vendors have provided thousands of cmdlets, but as yet, there is not full coverage of all the objects in the .NET framework. Thus if you need to use objects of those types (belonging to some less well known .NET Class). A good example is localisation. If you want to present a price in say US$, Norwegian crowns and UK Pound sterling. Assuming you know how to use the ServiceEx web services, the script looks like this:

"The UK price is: $($PriceUK.tostring('c'))" "The NO price is: $($priceNO.tostring('c',$noinfo))" "The US price is: $($priceUS.tostring('c',$usinfo))"

And the output looks like this:

Pretty easy, when you know how to manage .NET classes and can use XML web services. The .NET framework contains a wealth of classes that have value, depending what you are working with. Being able to just reach out and grab them, when there are no cmdlets, provides you with a lot of power. Plus, if you understand what is going on with objects, troubleshooting scripts becomes easier – if nothing else, the error messages may make a bit more sense.

In the next article I'll look at actually combining the information presented here with how to create these things using PowerShell V5.

As noted on the PowerShell Team Blog, Microsoft has published many new experimental resources for Windows PowerShell in the form of the DSC Resource Kit Wave 8. This latest release brings the number of rerources available to over ONE HUNDRED (138 for those of you who are counting – a 53% increase from the earlier release).

The sheer number of resoures now available is staggering – and I expect the pace of delivery here to continue as the team approach RTM for PowerShell 5 and Windows 10.

Tuesday, November 04, 2014

I’ve been working a lot recently with a nice package called ISESteroids. As an ISE user, the name got my attention before anything! As the name kind of indicates, the package improves PowerShell’s Integrated Scripting Environment.

So what IS ISESteroids? ISESteroids is a commercial module that you add into the ISE converting the ISE from a good development tool into a much better one. My view is simple: ISESteroids makes me able to write better code, more legible code quickly and easily.

Installing ISESteroids is trivial. Just download the package (it comes as an archive), unblock the archive (after download, right click the archive, select properties then select unblock). Then create an ISESteroids folder under your modules folder, and copy the contents of the archive there. It should look something like this:

Once the module is in place, you just need to add a line to your ISE Profile:

Start-Steroids

The first time you run this cmdlet, you have to accept the license agreement, but after a second or two, you can start to experience the added value ISESteroids gives you.

But what is that, I hear you say? There were several things I noticed after first installing ISESteroids. The first of which is that the whole UI changes. The top part of the ISE has the original tool bar expanded and with a second pull down tool bar with more tools. Plus the tool bar at the bottom of the ISE window has been enhanced and now includes a community information feed. This bottom tool bar also has a REALLY nice feature I’ve always wanted – the ability to just take the last command typed at the console and put it into the edit tab.

Here’s a before and after look (without, then with ISE Steroids installed and running)

versus

The community feed at the bottom is a very nice touch, although all the new tools was surprising (in a nice way). After using it a bit, on a system without ISESteroids, the ISE felt somewhat more primitive (not unlike using PowerShell V2’s ISE today!).

All those extra tools and a lot of the features in ISESteroids are focused on helping you to write better PowerShell code and streamlining that process as much as you can. In short: good practice built in, and more, more, more automation of the code development process.

Once I started writing scripts with ISESteroids enabled I saw some changes in the ISE’s Edit pane. Some language elements were marked with a ‘squiggle’ underneath. And the edit pane itself has been reformatted with some new elements. Here’s an example of a very simple script

Just above the number 1 and 2 are two things ISESteroids ‘complains’ about. The first thing is that I used an alias (LS) instead of the full cmdlet name (Get-ChildItem); the second thing is that I am using a string but it is delimited with a double quote, not a single quote. Single quotes, unless you are including variable expansion, are less performant. The third cool thing shown here is that ISESteroids keeps track of functions and shows you how often they are referenced. You can see here the FOO function was referenced just once just once. The final thing to notice is the new search bar – just type a function name, and PowerShell, jumps to that function definition in the code. Great for when you need to update a function definition you call a dozen times in your script!

ISESteroids also makes it easy to get rid of those squiggles. To fix the two issues above, you just hover over the bottom bar in the ISE windows and ISESteroids pops up messages like:

This makes it really simple to fix issues like this. I would have liked to have been able to just right click over the squiggle and select the fix from there – but the bottom of the window works too.

As you delve into using the ISE, just about every menu and tool bar is expanded. To name a few:

The File Menu now has an sub menu to open your profile files (you can open both console and ISE profiles).

The file Menu also has a Print menu item.

The Tools Menu now has a couple of new tools and options.

The Add-ons menu has new menu items for moving tool panes around the ISE UI. Useful if you are using some of the tools!

This is just scratching the surface. I’ve got a bit of a coding project coming up and so will be using ISESteroids more heavily and will gladly provide more feedback.

One final thing – ISESteroids is not a free product. Single use is €99 although there are volume discounts. BUT because the author is such a fan of the community, he has created what they call their ‘Helping Hands Programme’ – in effect they offer free NFR (not for resale) personal ISESteroids 2.0 Enterprise license in exchange for 3-5 hours of your work, helping them to make ISESteroids better known, and better documented. A very generous offer!

In summary, ISESteroids is a tool that adds value to the PowerShell ISE and helps you to write better scripts. If you are writing scripts and other PowerShell related artifacts as a key part of your job then this product is certainly worth the money.

Monday, November 03, 2014

As I noted in an earlier blog post, we have begun to see the contents of what eventually is to become PowerShell V5. Amongst the cool features that are to be delivered in V5, one of my favourite is the ability to define Classes and Enums in PowerShell. I'll leave Classes for another day (and possibly multiple blog posts), but let's look at Enums.

First, what is an enum? An enum is a type that create a list of named constants. In the .NET Framework, you find the System.Enum class – which implements enums.

You can think of an enum as all the proper values that some parameter can take. For example, if you were implementing a pizza application, you might have an enum called PizzaSize, representing the available sizes of pizza and another enum called PizzaToppings that contains the valid names of all the toppings you can put on your pizza.

Of course, you could have always used the ENUM feature of .NET, and there are a lot of enums already defined. For example, System.Net.Mail.MailPriority is an existing enum in the .NET Framework 4.5, which specifies the valid values for mail priority. This is a simple enum, with just three values: High, Low and Normal. If your code/script/function is passed a value for mail priority, it's always a good idea to validate it – and here's some PowerShell Code that can do this:

This function takes a string representing mail priority and returns true or false depending on whether it's valid. Here is the results of testing this function:

Now as you can see – the validation is case sensitive – thus 'High' is a valid mail priority, whereas 'high' isn't. You can get around that by fully spelling out the enum, and letting .NET work out the validity. Thus 'high' is invalid whereas [System.Net.Mail.MailPriority]::high (and [System.Net.Mail.MailPriority]::High) are both valid. This matters a lot if you are calling .Net method and passing enumerable values (e.g. mail priority).

Up until Version 5 of PowerShell, you could always use the [enum] class to validate and list all the valid values of existing Enums. But what you did not have, up till now, is the ability to create a real Enum in PowerShell. Of course, you could have used Add-Type, and specified the C# code but I don't regard that as quite the same thing as defining an enum in PowerShell directly.

In V5, it's trivial to create an enum. Just specify it's name, follow it by a script block with each enumerable value on a separate line. Like this:

Enum PizzaSize { Small Medium Regular Large ExtraLarge }

Note there are no commas separating the values,just a newline. I wonder if this is a limitation of the current release and maybe additional delimiters will come in later versions. We'll have to see!

Once you define this enum, you can then use the enum and can validate it:

This is pretty cool – and lays at least part of the foundation for you to be able to develop full .NET Classes in PowerShell.

There is at least one limitation I am aware of with Enums in PowerShell and that is that they are not persistent. Unlike the .NET Framework enums which are always available (one the relevant .NET Class Library is loaded!), you need to define enums in each script that uses them. That is, thinking about it, not such a great limitation – you just need to define your enums where you use them.

My preferred place is as as part of a module definition – just put your enums for your module in a file such as Enums.ps1 and put it into the module folder. Then, in the ScriptsToProcess key of the module's manifest, just specify Enums.ps1. That will dot-source them into your global environment and are then available for all the code you then run.

Enums are one important part of being able to develop a class in PowerShell. I'll be developing another article to describe how that works. I will probably wait till after the next drop of PowerShell V4, which is scheduled for November some time.

In a number of documents relating to OCS and Lync, I've seen discussion of Spam over IM (SPIM). I've not really seen much decent discussion of it, other than it's an issue. Most of the material seems to assume you know all about SPIM.

For those that are not familiar, you might want to look at RFC 5039. This document provides some great background in SPIM and other malevolent IM related stuff.