Tuesday, December 16, 2014

Sometimes When You Ask – You Get! Thanks Azure!

Over the past few months, I've been running a set of 1-day sessions for Microsoft SMB partners – these sessions are a combination of lecture and lab work. This material shows them how to position key Azure and Windows Server 2012 R2 features and gives them experience in using the products.

In a recent session, I was asked about Azure Backup and client systems. At that point (early September this year), the answer was no – Azure Backup did not support Windows 8 (or any client problem). The scenario here is the road warrior who never got back to base, but was forever somewhere in the cloud (via whatever networking they may find in their travels!). They just want their data backed up so if the laptop dies, is stolen or the disk itself dies – they can recover their data once the replacement hardware is up and running fully. Seemed to me to be a service I might buy for myself!

This seemed to me to worthy of consideration. So I posted a request over on Feedback.Azure.com. A couple of days later, I got surprise email from the Azure  Backup PM who wanted to chat with me about the suggestion I'd posted. We then had a conference call and I was able to explain the user need, and the potential for the suggestion. He listened, asked great questions then hinted that this is something they could consider for a future release. I did not hold out much hope of features any time soon, but it was nice to be listened to and to maybe having an impact down the road.

Imagine my surprise and delight when I read today's post on the Azure Team Blog, which announced support for Windows Cliewnt OS's! From asking to delivery in 14 weeks. Nice job!

Sunday, December 07, 2014

Type Accelerators and TypePx

Last week, I updated some earlier scripts related to Type Accelerators over on my PshScripts blog – and I've had some great feedback. Kirk Munro (@Poshoholic on twitter and all around PowerShell superstar) pointed out there is a TypePX module he's published to GitHub.

As to be expected of anything Kirk touches, the TypePX module is rich and well implemented. His module is production ready – so you could easily copy it to your modules folder and start to use it. The TypePx functions are pipeline friendly and have good error handling. 

What I've published is much more simple and designed for a different audience. The whole idea of what I published, and indeed the whole point of my PshScripts blog, is to illustrate simple concepts, apis, etc in a simple script. In this case, the essence of type accelerators is wrapped up in a few lines of code. This is what I strive to publish in Pshscripts – showing you how to do one thning simply (per script!). What Kirk publishes is enterprise grade production scripting. I readily admit they are different – but I'd like to think there is room for both. One ofr learning with, one for using in production.

Saturday, December 06, 2014

Type Accelerators – And a Module

Over the years, I've written about type accelerators and PowerShell. A type accelerator is simply a synthetic type name that you can create to serve as an alias to another type name. For example, you could use the int16 type to refer to the System.Int16, or guid instead of [system.guid]. Type accelerators are meant to simplify handling of types by IT Pros in PowerShell scripts.

TAs were first introduced in a beta of PowerShell V2, and I posted code that worked (then). However, I have been recently updating my script library blog (http://pshscripts.blogspot.com), I discovered that TAs stopped working that way. After some fun and effort, I've now found hot how they work today, and how you can play with them!

TAs work by just providing you with an alias to a full type name. To some degree, TAs make up for the lack of a Using statement such as in the C# language. Some common TAs in use include [ADSI], [WMI], [String], [regex] and many more.

This week, I have published a new TypeAccelerators modules. This module contains scripts that define 4 TA-related functions:

  • Get-TypeAccelerator– this gets the TAs active in your current PowerShell Session. This function also takes a parameter (AliasRE) which is a regular expression over the type accelerators to return.
  • Measure-TypeAccelerator – this just returns a count of the TAs active.
  • New-TypeAccelerator – this adds a new type accelerator that aliases an existing type
  • Remove-TypeAccelerator – this removes a type accelerator from your current system.

Here's a screen shot of using these TAs

 image

The scripts also create aliases for these functions: GTA, CTA, NTA and RTA as you might imagine. The module also includes an about_ file for help – you get this importing the module!

You can get the module at http://www.reskit.net/powershell/typeacceleratosr.zip. I will also look to publish this module to the new PowerShell V5 Internet module repository (and maybe Chocolatey too if I get time).

A small footnote: this module and the scripts therein are intended to illustrate the concepts around type accelerators. They lack any sort of pipeline friendliness or error handling. So if you decide to make use of the concepts here – make sure you add the production quality aspects to your code, leveraging mine.

Thursday, December 04, 2014

Azure Documentation on GitHub

Late last night, I was looking for some information on a topic within Azure. After a search, I ended up here: a good page describing Azure cloud services. As I read through it, I noticed that at the bottom there was this link

image 

The highlighting is mine, but I looked at this for a bit before the import sunk in: MS is open sourcing the Azure documentation! WOW!!

So I went off to GItHub (in this case to https://github.com/Azure/azure-content/blob/master/articles/cloud-services-what-is.md) to have a look. From here, if you create a GitHub id, you can create a fork, edit one (or more documents) and submit them back via a pull request. Once approved the documentation goes live.

What a cool idea – well done Microsoft.

Monday, December 01, 2014

What is Coming in the Next Version of Hyper-V?

Savision have just sent mail about an upcoming web cast on this topic. On Dec 2 and Dec 4, Symon Perriman (Microsoft Senior Technical Evangelist) will co-host (with Savision) that will cover an overview of the new capabilities coming in the next Version of Hyper-V. I can't wait!

Mark your calendar for these dates:
Tuesday, December 2, 2014 | 3:30 PM CET/ 9:30 AM EDT   
Thursday, December 4, 2014 | 8:00 PM CET/ 2:00 PM EDT 

Register now for these exclusive webinars by Microsoft's Symon Perriman as there is limited space available.

Friday, November 28, 2014

Keeping up with Azure PowerShell Tools Changes

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.

del.icio.us Tags: ,,

New Blog Layouts For My Blogs

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

Capturing Different Types of PowerShell Output

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:

Write-ToStreams 4>4out.txt 2>2out.txt

del.icio.us Tags: ,

Wednesday, November 26, 2014

Creating a Hyper-V Generation 2 Disk with PowerShell

del.icio.us Tags: ,

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

Writing Classes With PowerShell V5 – Part 2

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:
Add-Type @' 
public class Aeroplane
   {
     public string Model = "Boeing 737";   
     public int    InFleet = 12;
     public int    Range = 2400;
     public int    Pax   = 135;
   } 
'@
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:
image
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:
Dir c:\foo\*.ps1 | Select-Object name,fullname| gm
  TypeName: Selected.System.IO.FileInfo
Name        MemberType   Definition                                  
----        ----------   ----------                                  
Equals      Method       bool Equals(System.Object obj)              
GetHashCode Method       int GetHashCode()                           
GetType     Method       type GetType()                              
ToString    Method       string ToString()                           
FullName    NoteProperty System.String FullName=C:\foo\RESTART-DNS.PS1
Name        NoteProperty System.String Name=RESTART-DNS.PS1          
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:
PSH [C:\foo]: $Filesize = @{
    Name = 'FileSize   '
    Expression = { '{0,8:0.0} kB' -f ($_.Length/1kB) }
}

Dir c:\foo\*.ps1 | Select-Object name,fullname, $Filesize
Name                   FullName                  FileSize               
----                   --------                  -----------               
RESTART-DNS.PS1       C:\foo\RESTART-DNS.PS1         1.1 kB               
s1.ps1                C:\foo\s1.ps1                  0.1 kB               
scope.ps1             C:\foo\scope.ps1               0.1 kB               
script1.ps1           C:\foo\script1.ps1             0.5 kB               

PSH [C:\foo]: Dir c:\foo\*.ps1 | Select-Object name,fullname, $Filesize| gm
   TypeName: Selected.System.IO.FileInfo
Name        MemberType   Definition                                  
----        ----------   ----------                                  
Equals      Method       bool Equals(System.Object obj)              
GetHashCode Method       int GetHashCode()                           
GetType     Method       type GetType()                              
ToString    Method       string ToString()                           
FileSize    NoteProperty System.String FileSize = 1.1 kB       
FullName    NoteProperty System.String FullName=C:\foo\RESTART-DNS.PS1
Name        NoteProperty System.String Name=RESTART-DNS.PS1          
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.

Monday, November 24, 2014

Dell Bios Module

I have previously written about hardware vendors shipping PowerShell hardware related modules. I just ran across another one – this time a BIOS module from Dell, which comes with a rather cool provider! You can get the module itself from Dell's Mobile Solution site.

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:

image

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:

image

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:

imageThis 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

Using Pre-Release Software Not Always A Great Experience

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:

imageWeird, 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:

imageJust 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.

So for the foreseeable future, I'm stuck with using a partly broken beta build. I can live with OneGet being broken in exchange for the other goodies in V4. And yes, this bug has been reported on Connect (https://connect.microsoft.com/PowerShell/Feedback/Details/1037088). Feel free to vote it up!

The joys of using Beta software!

Friday, November 21, 2014

A New Build of PowerShell – Chocolatey Regained

Having posted previously about a recent PowerShell V5 interim build that resulted in Chocolatey not being available by default – as if by magic, Microsoft have issued a new build of PowerShell V5 Preview AND it's includes Chocolatey by default. You can get more details from the PowerShell team Blog.

This build only operates on Windows Server 2012 and 2012 R2, and Windows 8.1.

Technorati Tags: ,

Wednesday, November 19, 2014

Yet Another PowerShell V5 Preview Build!

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!

To get the new build, go here: http://www.microsoft.com/en-us/download/details.aspx?id=44987. This link has the binaries for X64 and x86 systems plus one for what appears to be windows RT, which would be very cool. More on this when I get home to play on my RT Windows Surface device.

In the mean time: let the downloads begin!

Technorati Tags:

Tuesday, November 18, 2014

Chocolatey Lost, Chocolatey Found

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:

Register-PackageSource -Name chocolatey -Provider PSModule `
-Trusted –Location http://chocolatey.org/api/v2/

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.

Technorati Tags: ,

Friday, November 14, 2014

More 3rd Party PowerShell Goodness – this time from EMC

Another company, EMC, joins the ever lengthening list of 3rd party firms that are incorporating PowerShell, or a PowerShell interface into their products. If you go over to http://velemental.com/2014/07/07/powershell-module-for-emc-protection-rest-api/, you can see more details of the REST api and the cmdlets.

del.icio.us Tags: ,

Wednesday, November 12, 2014

Microsoft takes .NET Open Source AND Cross-Platform

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.

Wow!

Technorati Tags: ,

Tuesday, November 11, 2014

CBT Nuggets Publish a Course for Microsoft Exam 70-337

I see that CBT Nuggets have just announced the release of their video training course Microsoft Lync Server 2013 70-337.

This course covers all the key parts of the syllabus for the 79-337 exam along with some exam preparation tips and a case study to help you further prepare.

I've not yet looked at the videos in the course, but CBT Nuggets material is usually of a good standard. I'd be interested in any feedback.

Monday, November 10, 2014

Writing Classes With PowerShell V5-Part 1

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:

image

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.

image

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:

.

image

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:

# Create an empty massage
$EmptyMsg = New-Object System.Net.Mail.Mailmessage

# Create a message from and to
$To= 'tfl@psp.co.uk'
$Fm='doctordns@gmail.com'
$MailMsg = New-Object System.Net.Mail.MailMessage $Fm, $To

So What?

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:

# Get Curency conversion rates
$From = 'GBP'
$Tous  = 'USD'
$Tono  = 'NOK'
$CurrencyConvertor = New-WebServiceProxy "
http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"
$USrate = $currencyConvertor.ConversionRate($from,$tous)
$NOrate = $currencyConvertor.ConversionRate($from,$tono)

# Calculate price
$priceUK = 12345.669
$priceNO = $PriceUK * $NOrate
$priceUS = $PriceUK * $USrate

# Convert to nice strings
$usinfo = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-us')
$Noinfo = [System.Globalization.CultureInfo]::CreateSpecificCulture('no-nb')

"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:

image

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.

 

PowerShell Desired State Configuration – More Resources

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.

As Clifton Chenier sings: Laissez les bon temps roulez.

Tuesday, November 04, 2014

Writing Better PowerShell Scripts with ISESteroids

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:

image

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)

image

versus

 image

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

image

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:

image

image 

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.

For more information about the product, see the documentation: http://www.powertheshell.com/isesteroids2/documentation/.

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.

Technorati Tags: ,,

Monday, November 03, 2014

Enums in PowerShell V5

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:

# Enums.ps1
Function Confirm-MailPriority {
param ([string] $mailpriority)
if ([enum]::IsDefined(([System.Net.Mail.MailPriority]),$mailpriority))
   {Return $true}
Else
   {return $false}
}

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:

image

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:

$size = [pizzasize]::large
[enum]::IsDefined(([pizzasize]),$size))  # True!

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.

Technorati Tags: ,,,

Sunday, November 02, 2014

PowerShell OneGet Monthly Call

I am not quite sure how this got out here, but am glad it did. This (https://t.co/mkafiMJR9T) is a web cast covering the current state of play with the OneGet feature of PowerShell V5.

This is awesome stuff – keep it up!

Spam and IM

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.

Technorati Tags: ,,,

Wednesday, October 22, 2014

Managing Zip Files with PowerShell V5

In a recent blog post, I noted the arrival of PowerShell V5 preview within the technical preview of Windows 10. A slightly later version than is available for installation on down-level operating systems ( I use the latest V5 preview version both on my Windows 8.1 laptop and my main home workstation (which runs Server 2012 R2).  While Desired State Configuration is the ‘big’ new feature in V5, there are a lot of other cool features in V5, including the ability to manage zip files with PowerShell.

The later V5 preview versions come with two new cmdlets or managing  ZIP files:

  • Compress-Archive
  • Expand-Archive

The Compress-Archive cmdlet takes an array of file names (specified via the –Path parameter) and compresses them into an archive file (specified by the -DestinationPath Parameter). You can also specify the level of compression – the valid values are NoCompression, Optimal, Fastest. Fastest means that the compression is less than  Optimal, but Optimal should produce slightly smaller .ZIP files. Optimal, however, takes more CPU time – but there’s not much difference for smaller files. To have Compress-Archive update some or all the files in the archive, use the –Update parameter. This parameter updates the archive with the specified files. Thus you can update a single file in an archive should the need arise.

The Expand-Archive cmdlet expands the files in the archive (specified by the –Path parameter) into the folder specified by the –DestinationPath parameter. To avoid being asked for permission to do the expansion, you can speciy the –Force parameter.

 

Here’s an example of some archive file manipulation

 

PSH [C:\foo]: ls c:\foo\*.txt

    Directory: C:\foo
Mode                LastWriteTime         Length Name                                         
----                -------------         ------ ----                                         
-a----       26/07/2014     15:59            431 atia.txt                                     
-a----       19/06/2014     17:25          18890 history.txt                                  
-a----       06/03/2014     15:09           1027 hosts.txt                                    
-a----       06/08/2014     10:05             37 NAMES.TXT                                    
-a----       24/09/2014     06:58           1877 trans1.txt                                   

PSH [C:\foo]: (ls *.txt | measure -sum -Property length).sum
22262

PSH [C:\foo]: Compress-Archive *.txt -DestinationPath .\aaa1.zip -CompressionLevel Fastest

PSH [C:\foo]: Compress-Archive *.txt -DestinationPath .\aaa2.zip -CompressionLevel Optimal

PSH [C:\foo]: Compress-Archive *.txt -DestinationPath .\aaa3.zip -CompressionLevel NoCompression

PSH [C:\foo]: ls c:\foo\aaa?.zip

    Directory: C:\foo

Mode                LastWriteTime         Length Name                                         
----                -------------         ------ ----                                         
-a----       21/10/2014     18:33           2172 aaa1.zip                                     
-a----       21/10/2014     18:33           2039 aaa2.zip                                     
-a----       21/10/2014     18:33          22783 aaa3.zip                                     

PSH [C:\foo]: Expand-Archive c:\foo\aaa1.zip -DestinationPath c:\foo\expanded -Force

PSH [C:\foo]: dir .\expanded

    Directory: C:\foo\expanded

Mode                LastWriteTime         Length Name                                         
----                -------------         ------ ----                                         
-a----       21/10/2014     18:34            431 atia.txt                                     
-a----       21/10/2014     18:34          18890 history.txt                                  
-a----       21/10/2014     18:34           1027 hosts.txt                                    
-a----       21/10/2014     18:34             37 NAMES.TXT                                    
-a----       21/10/2014     18:34           1877 trans1.txt
                                   

In summary, two new and somewhat overdue cmdlets that make your life easier!

Technorati Tags: ,,,

Monday, October 20, 2014

Another PowerCamp is Over

Last weekend, I held another PowerShell PowerCamp event – we had 19 attendees in all for two days of PowerShell. It was a great weekend, topped off by Tom Arbuthnot coming in on the Sunday to deliver a guest lecture.  I really enjoyed it, but it was a lot of work! And from the mail I've had, the attendees got a lot out of it.

Thanks to the folks at Microsoft, particularly Claire Smyth, for all their help in making the weekend a success.

During the event, there were several ideas put forward to a next event. One suggestion was a more advanced weekend, particularly looking at DSC and the new things in Version 5. A V5 PowerCamp could be fun! Ideas as to future events are most welcome.

Technorati Tags: ,

PowerShell Version 5 in Windows 10 Preview

Like a lot of people, I’ve downloaded and been playing with the previews of Windows 10 (client and server). About the first thing I did was to check out PowerShell and was delighted to find it contains a very late drop of the PowerShell V5 code – marginally later than the WMF Preview shipped in September.

My Server 2012R2 workstation, which has the September V5 drop reports:

image

Meanwhile, in the Windows 10 Server preview, we see:

image

As you can see, Windows 10 has a slightly newer version of PowerShell V5. The release notes don’t clarify what has changed, but I’d have expected the 9841 to be just a bug fixed fork of 9814.

This new version of PowerShell brings some big changes, not least of which is the improvements and enhancements to Desired State Configuration – no doubt this will feature large in the eventual launch of Windows 10 Server (Server 2015??).

But there are also a bunch of smaller changes that I also am very keen to see go mainstream. These include:

  • Archive (.ZIP file) cmdlets
  • Changes to –item noun to enable symbolic links
  • The ability to develop classes (and enums) using PowerShell
  • Improvements in DSC authoring within the ISE
  • PowerShell transcripts within the ISE
  • Better script tracing

PowerShell V5 looks like being a block buster! I’ll be writing blog articles about each of these new features along with some usage of them for your delight!

Technorati Tags:

Tuesday, September 30, 2014

PowerCamp Power Guest–Tom Arbuthnot

On Oct 18/19th, I run the next PowerShell PowerCamp – a 2 day PowerShell jump start event. Over the course of 2 days, I run through the basics of PowerShell – from Cmdlets/Objects/Pipelines, through formatting, the ISE, the language and its syntax, functions and modules, and Desired State Configuration (DSC). You bring your laptop and while I’m lecturing, you are banging out PowerShell to manage a set of VMs you bring along!
As part of the event, I always try to get another guest speaker, who I ask to talk about PowerShell in general. What are the things they have learned (which attendees will have to to)? What are their best practices? For this event, I am pleased to announce we will have the presence of Tom Arbuthnot, a superstar Lync MVP and Lync Consultant (and a Lync MCM!), and a great PowerShell evangelist. Tom’s spoken before at these events, and his talks are good and very entertaining.
I still have a few places left on this event – so if you want a great jump start to PowerShell, or to review the basics and more, then contact me at DoctorDNS@Gmail.Com !

Thursday, September 18, 2014

Azure for Longer Term Backup

I’ve been teaching the AOTG (Ahead of the Game) partner training around the UK, and shortly in Eire. It’s been very interesting talking to Microsoft’s SMB partners and looking at how they sell and utilise Azure. One of the Azure Products this training is advocating is Azure Backup. Last week, when I was teaching this in Manchester, one delegate pointed out that the big downside to Azure backup was that there was not much of a retention period and as such was not helpful to the delegate’s customers.

Fast forward a few days, and the wish has come true. I had a conference call this morning with the Azure backup who told me that this request had been heard loud and clear and is now in place. He pointed me to the blog post at: http://azure.microsoft.com/blog/2014/09/11/announcing-long-term-retention-for-azure-backup/

Sure enough, you can get all the backup you need (well all reasonable backups!). And the maximum retention period is 9 years, as the blog post explains.

One word: Awesome!

del.icio.us Tags: ,,

Saturday, August 30, 2014

Documentation–documenting variables in a script/function

A few weeks ago, I gave a PowerShell course during which the issue of documentation came up. The point I made was documentation is a good thing – and the more the better. The delegates really liked the comment based help approach. But it often does not go quite far enough.

One additional thing you can do is to document individual variables. Each variable object lives in the Variable: drive. Variables are , like everything PowerShell, an object. When you get child items of a variable, the variable is returned of the type System.Management.Automation.PSVariable. There are some special PowerShell variables (QuestionMarkVariable, LocalVariable, SessionStateCapacityVariable, and NullVariable). All of these objects have a Description property which enables you to describe each variable.

So you could do this:

$I = ‘10.0.0.100’
(dir variable:I).description  = ‘the new IP address for the new server’
$iold = ‘10.0.1.200’
(dir variable:iold).description  = ‘the new IP address for the new server’
Dir Variable: | Format-Table name,description –a

I’ve not used this approach much, but I probably do so in the future for production scripts at least!

Friday, August 29, 2014

Azure Machine Learning – What is it and Doing it In Azure

Azure Machine Learning is another of those features of Azure I've not gotten around to playing with. Andrew Fryer of Microsoft has produced a couple of good articles on the subject, both in general and Azure specific.

Machine Learning appears to be the new marketing buzzword previously known as data mining. Given enough data, you can mine it to find gold is the basic concept. In his first article, Fryer looks at what Machine Learning (ML) is and some of the basic tasks. In the second article, Fryer looks at exploring and evaluation of the technique to see if it's of value to an organisation.

Desired State Configuration Resource Kit–Wave 6

The PowerShell team has just released an update to the DSC resource kit – bringing the total number of DSC resources to over 80! While the bulk of the resources in the resource kit are ‘experimental’ – they seem to me to be very stable (continuing the PowerShell team’s ability to ship rich, useful, and reliable beta code).

And even better, the PowerShell team seem to have gone back to their old roots in terms of time to market. They appear to be releasing as they develop (and long may this continue). Thus, the new SafeHarbor DSC resource, this was finished after Wave 5 was released but before Wave 6 was ready so the PowerShell team published it separately, then publish it (with updates and bug fixes) a few weeks later in the Wave 6 drop. I can’t tell you how good this feels after so long under the cone of silence.

This latest drop has some very interesting resources, including the xChrome and xFirefox resources that help to deploy these two browsers. The Group resource shipped with PowerShell 4 is updated to provide support for cross-domain account lookups as well as for UPN-formatted names. The new xRemoteDesktopAdmin resource enables. Additionally, Wave 6 has a number of bug fixes to earlier waves. Again – the ability to get these fixes quickly is both useful and much appreciated. 

The  DSC story is slowly coming clearer with both the July drop and these continuingly improving resources. And with Chef integrating with DSC, DSC’s future looks very rosy.  If you are looking to find out a bit more about DSC – I’ll be covering the basics on the PowerShell PowerCamp event in October.