Creating a C# CmdLet

So Powershell comes with a lot of commands/CmdLets but as a developer I’m always interested in how I might write my own. Whilst it’s likely that combining existing commands might produce the results you’re after, if it doesn’t we can resort to writing our own command using C#.

Getting Started

  • Create a new Class Library project
  • Go to the project properties and target the version of .NET supported by your installed version of Powershell (to find this out simply type $PSVersionTable into Powershell and check the CLRVersion)
  • Add a reference to System.Management.Automation to locate this browse to C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0
  • The namespace we need to add is System.Management.Automation

Hello World CmdLet

Now we’ve got everything set-up we need to make our CmdLet do something. Here’s the source for a good old HelloWorld Cmdlet

[Cmdlet(VerbsCommon.Get, "HelloWorld")]
public class GetHelloWorld : Cmdlet
{
   protected override void ProcessRecord()
   {
      WriteObject("Hello World");
   }
}

The CmdLetAttribute takes a string for the verb, in this case I’m reusing the VerbsCommon.Get string. The next requirements is the noun, the name of the Cmdlet. So in this case the two go together to give us the Cmdlet Get-HelloWorld.

We derive our class from Cmdlet as we’re not dependent upon the Powershell runtime, if we were we’d derive from the PSCmdlet.

Importing and using the new CmdLet

Once we’ve built our CmdLet and assuming it’s been built with the same version of .NET as supported by the installed Powershell, we can import the “module” into Powershell using

Import-Module c:\Dev\MyCmdLets.dll

Obviously replacing the path and DLL with the location and DLL you’re installing

Once imported we can simply run

Get-HelloWorld

Autocomplete also works if you type Get-He then press tab and you’ll find Get-HelloWorld presented.

If you need to rebuild your Cmdlet you’ll need to close the Powershell instance to remove the instance from it, I tried Remove-Module MyCmdLets but this only removes its availability to Powershell, i.e. you can no longer run it, but I guess, like in C# applications, once the module is in the AppDomain you cannot fully unload it.

Parameters

Let’s add a parameter to the Cmdlet.

[Cmdlet(VerbsCommon.Get, "HelloWorld")]
public class GetHelloWorld : Cmdlet
{
   [Parameter(Mandatory = true)]
   public string Name { get; set; }

   protected override void ProcessRecord()
   {
      WriteObject("Hello World " + Name);
   }
}

So now, we’ve added a mandatory parameter Name. When we run the Get-HelloWorld Cmdlet we can now supply the name, thus

Get-HelloWorld -Name Scooby

Returning objects

So far we’ve returned a string, but what about if we want to return and object or better still multiple objects, like Get-Process might.

[Cmdlet(VerbsCommon.Get, "HelloWorld")]
public class GetHelloWorld : Cmdlet
{
   protected override void ProcessRecord()
   {
      WriteObject(new HelloObject { Name = "Scooby", Description = "Dog"} );
      WriteObject(new HelloObject { Name = "Shaggy", Description = "Man" });
      WriteObject(new HelloObject { Name = "Daphne", Description = "Woman" });
   }
}

public class HelloObject
{
   public string Name { get; set; }
   public string Description { get; set; }
}

Now running this from Powershell will list two columns, Name and Description and three rows with the name and description as per our objects.

Better still we can now write commands such as

Get-HelloWorld | where {$_.Description -eq "Dog"}

References

Cmdlet Methods

Writing Powershell command (.ps1) files

In a previous post I started to look into using Powershell, but ofcourse the power of commands/Cmdlets comes when they’re either combined or whereby our most common commands exist in files to be run again and again.

So let’s turn an often used command into a ps1 file.

Windows PowerShell ISE (Integrated Scripting Engine)

From the Windows search box (ctrl+R) we can run up the Windows PowerShell ISE. This gives us, both an editor and also a command prompt for writing and testing our command scripts.

You can also run this application from the command line using powershell_is or better still via the alias ise.

In the editor let’s type

Get-Process | where {$_.CPU -gt 1000}

Now save this file as Top-Cpu.ps1

Running our new command

We can simply drag and drop a ps1 file from Windows Explorer onto the Powershell window to fill in the fully qualified path on the command line, pressing enter we can then run the file. Obviously if you know the full path you can do this yourself by typing the same into the command prompt.

Specifying parameters

It may be that our ps1 file is perfect as it is, but it’s also quite likely we’ll want to allow the user to change some values in it at runtime, i.e. using command line arguments/parameters.

To specify parameters in our script we write

param(cpu=1000)

This defines a parameter named cpu and gives a default value, in this case 1000. If we change our script to look like this

param($cpu=1000)
Get-Process | where {$_.CPU -gt $cpu}

where you’ll notice $cpu is the placeholder/variable where the parameter is used. We can now run this script as Top-cpu.ps1 and the default parameter is used. Or we might write Top-cpu.ps1 7000 to supply a new parameter.

Multiple parameters

We can command separate our parameters to include multiple params, like this

param($value=1000, $field="CPU")
Get-Process | where {$_.$field -gt $value}

Maybe not so useful in this specific script, but you get the idea.

References

Windows PowerShell: Defining Parameters

Powershell $profile

What’s the purpose of the $profile

The $profile (like a bash script configuration) allows us to configure the way our Powershell command shell looks, or sets the default location, we can add commands and aliases etc.

Where’s the $profile and does it exist?

Typing the following will result in Powershell telling us where the Microsoft.PowerShell_profile.ps1 file is expected to be

$profile

Just because $profile outputs a path, does not mean there’s a file’s there. It’s simply telling us where it goes to get the profile, we may still need to created one, instead we can use the following

We can find out whether a $profile already exists using

Test-Path $profile

Test-Path determines whether all elements of a path exists, i.e. in this case, does the file exist

Creating the profile file

Typing

New-Item -path $profile -itemType file -force

will create a new item (in this case a file) at the location (and name) supplied by the $profile variable. The force switch ensure the file is overwritten if it already exists.

The ps1 file is just a text file, so from the command line you can run Notepad or powershell_ise (or ofcourse from the Windows GUI you can do the same) and edit the file, allow us to enter the commands that might want available from session to session.

What resource names exist in my WPF application

Occasionally I need to get at the names of the resources in an assembly, usually this coincides with me trying to use a resource which either doesn’t exist of I otherwise make a typo on its name.

This little snippet simply allows us to iterate of the resources in an assembly and returns an array of the key names

public static string[] GetResourceNames(Assembly assembly)
{
   string resName = assembly.GetName().Name + ".g.resources";
   using (var stream = assembly.GetManifestResourceStream(resName))
   {
      using (var reader = new System.Resources.ResourceReader(stream))
      {
         return reader.Cast<DictionaryEntry>().
                    Select(entry =>
		       (string)entry.Key).ToArray();
      }
   }
}

Throwing/rethrowing exception from a continuation onto the Dispatcher

Even with async/await we still have a need for using Task continuations and ofcourse we need to handle exceptions within, or from, these tasks and their continuations.

A problem can occur in a WPF application for example, where the exception seems to get lost, for example from a ICommand handler I has such a situation where I couldn’t seem to catch the exception and neither did it propagate through to any unhandled exception handlers.

In the example below, we’ll assume that RunAsync returns a Task and we want to do something after the task completes on the calling thread (for example if the calling thread was the UI thread), we might have something like this

RunAsync().
   ContinueWith(tsk =>
   {
       // do something UI specific
   }, TaskScheduler.FromCurrentSynchronizationContext());

If we have exceptions occur in the RunAsync method, then we would maybe write something like this

RunAsync().
   ContinueWith(tsk =>
   {
      if(tsk.IsFaulted)
          throw tsk.Exception;

       // do something UI specific      
   }, TaskScheduler.FromCurrentSynchronizationContext());

If you don’t like the exception code mixed with the non-exception you could ofcourse create a continuation that is only called when a fault is detected, using TaskContinuationOptions.OnlyOnFaulted

This will correctly handle the exception and throw it, but you’ll probably find it just seems to disappear after the throw and doesn’t even appear in the various unhandled exception handlers – meaning the worse case occurs for an exception, in that it simply disappears.

What we really want is to throw the exception onto the Dispatcher thread so that an unhandled exception handler can at least alert the user that a problem exists. We can do this using the following line of code

Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { throw ex; }));

Now, unfortunately this means the stack trace is lost as we’re not simply re-throwing the original exception, but on the plus side we now actually see the exception.

Finally decided to learn a little Powershell

For years I’ve been thinking of learning Powershell, but I’ve never really had a real need for it, so subsequently it got neglected for such a long time.

I’ve finally decided to spend some time with it and see what it can do for me. Let’s start by looking at some of the basics to getting started with Powershell.

Commands (or Cmdlets)

Built-in commands are also known as Cmdlets, although I’ve also seen that some users prefer to think of Cmdlets as multiple commands – more like batch files. Either way, I’ll use the word interchangeably.

Note: Commands are case-insensitive

Let’s jump right in

Let’s have a look at an example command in Powershell

Get-Process | where {$_.CPU -gt 1000}

In the above, the command is Get-Process. This returns a list of the current processes running on your computer. Running Get-Process will result in eight headings (on my machine). Get-Process actually returns data as objects which we then pipe using | to the where clause.

The where clause syntax uses the braces {} to group together to form a block (much like blocks in C++ etc.). Within this block we use the $_ syntax which is a placeholder which in essence means “the current value” from the Get-Process command. In other words each item return from Get-Process is piped to the where clause and the $_ indicates the current value. From this we use standard object oriented style dot notation to get at a property on the item $_, in this case the property is CPU.

Note: The $ is used for to denote a variable, whether it’s supplied by default by Powershell or created by the user

Next up with have the -gt which as I’m sure you can determine, means “greater than” and ofcourse on the right hand side of this expression is the value we want to test for.

How do we determine what properties exist on an object?

In the previous command we used the CPU property of the results from Get-Process but how did we know that property existed and are there more properties we could have used? Ofcourse, there’s documentation which can tell us such things, but we can also use another Powershell command to tell us.

By typing the following

Get-Process | Get-Member

We can pipe the Get-Process object into Get-Member which will output a list of properties (and other members) of the type returned by Get-Process. If you run this you’ll find the CPU property (and many others).

Actually using the Powershell command prompt we can also view the properties by pressing ctrl+space after the dot, this allows us to list all available member names for an object. In the case of Get-Process this will list 122 possible member names.

Getting help

Powershell’s help system is very powerful. Simply type

Get-Help

to view the help on the Get-Help command. From here you’ll see you can type

Get-Help Get-Process

which will display help on the Get-Process command. We can also view examples for this command using

Get-Help Get-Process -examples

Aliases

Some commands are also aliased, meaning our original Get-Process | where {$_.CPU -gt 1000} can be rewritten as

ps | where {$_.CPU -gt 1000}

ps is simply an alias to the longer winded Get-Process and we can find an alias (if one exists) using the following

Get-Alias -definition Get-Process

Ctrl+Space

I noted previously that you can get a list of member names by pressing the combination ctrl+space after the dot, this is also useful after the – operator, for example when looking for alternatives to gt we can type – then ctrl+space and a list of options appears which includes, bnot, eq, f and more.

Symlinks/Junctions in Windows

I’m not sure which version of Windows these became available in, but a useful feature (as per *nix) is the capability of creating a link from one folder to another.

So for example, I have source code which relies on a set of libraries which are supplied in a zip (i.e. no NuGet or other packaging/versioning). So I tend to create a folder with the version number in it to make it easy to immediately see what version I’m using.

Great, but the problem with this approach is I also have tooling which automatically deploys these files and post build events which do similar things. Updating these every time I get a new version is repetitive and easy to make a mistake. Plus, I’m basically lazy, if I do something once I don’t want to do it again.

So it would be far better if we created a symbolic link to the newly downloaded zips/files with a name that all the tooling can expect, for example I’ll instead create a symlink named Latest which points to the actual version (this also means I could switch version if I want easily).

To create such a link we simply use

mklink /J Latest MyLibsv1.234

this command will create a junction (or symlink) named Latest and the folder it links to is MyLibsv1.234

Now we might use nant a batch file or some other means to do this for us, but when the link’s created you cannot update it (or so it seems), instead you need to delete it using

rd Latest

So now our post build events and/or other tooling can just refer to the folder Latest and everything works smoothly.

When it’s time to deploy MyLibsv2.0 we just delete the junction and create it again.

My Visual Studio 2012 C++ 32-bit application is “exe is not a valid Win32 application”

I have a C++ application which I’ve just updated to be built using Visual Studio 2012. The original solution was developed in Visual Studio 2010, so I updated the project properties, Configuration Properties | General | Platform Toolset to Visual Studio 2012.

The application is a 32-bit application, everything was built for 32-bit and all worked well on Windows 7, but on Windows XP (which is still used by some of our users) it failed with the “exe is not a valid Win32 application”.

Checking the configuration manager suggested it was indeed a 32-bit application. Running dumpbin /headers app.exe confirmed it definitely was a 32-bit application but XP said no it wasn’t.

Here’s the thing – I hadn’t noticed when setting the Platform Toolset, there was a second option Visual Studio 2012 – Windows XP (v1100_xp).

Changing to this toolset fixed the problem. So 32-bit does not mean 32-bit on all Windows.

Populating random data

I was working on a small utility which generates XML based upon a given class (which is already XML serializable). I wanted to generate random data just so I could see how the end XML looked in case I needed to tweak the XSD.

Source for the utility is available on AutoGenXml.

I figured somebody must have already approached such a problem, and thankfully I was right. There are a few solutions for populating object data. I ended up trying out two different libraries, AutoFixture and NBuilder.

Disclaimer: I have literally only just started using these libraries, so I’ve yet to find all the good and/or bad points of each library.

Let’s take a real quick look at what these libraries can do.

Test object

Let’s start out by defining an object hierarchy to test this two libraries out on. Mine looks like this

public class Album
{
   public string Title { get; set; }
   public string RecordLabel { get; set; }
   public Artist Artist { get; set; }
   public string Genre { get; set; }
}

public class Artist
{
   public string Name { get; set; }
   public BandMember[] Band { get; set; }
}

public class BandMember
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Talent { get; set; }
}

AutoFixture

AutoFixture source can be found on AutoFixture.

We can create objects with AutoFixture (hence using it as the factory for our objects) and it returns a populated object hierarchy.

Let’s look at the code (it’s pretty simple)

var fixture = new Fixture();
var album = fixture.Create<Album>();

The album will now have data in all fields and the Artist and BandMember properties are also created and data supplied.

Whilst it’d obviously be easy enough for us to create an object multiple times if we wanted a list of Albums but AutoFixture also supplies this code to do the same thing

var fixture = new Fixture {RepeatCount = 10};
var albums = fixture.
                 Repeat(fixture.Create<Album>).
                 ToArray();

NBuilder

NBuilder source can be found on NBuilder.

NBuilder also supplies a factory pattern for both creating our objects and populating the object.

Here’s the code

var album = Builder<Album>
               .CreateNew()
               .Build();

NBuilder uses a fluent style interface and offers options for creating multiple items (i.e. an IList<> of objects). There’s also a mechanism for us to intercept the object population step and supply our own data. So whilst in the usage shown above, we don’t have the object heriarchy created, we can create this ourselves fairly easily using

var albums = Builder<Album>
   .CreateListOfSize(10)
   .All()
      .With(a => a.Artist = Builder<Artist>.CreateNew()
         .With(b => b.Band = Builder<BandMember>
                    .CreateListOfSize(3)
                       .Build().ToArray())
	.Build())
   .Build();

References

This is a great post on using NBuilder with Faker which allows us to populate the objects with more realistic data than the default process.

Compiling C# code at runtime

Occasionally we might come across a problem which lends itself well to the idea of C# code being compiled at runtime, maybe we’ve created some script like plug-in or in my case I wanted to generate sample XML data from xsd.exe generated classes at runtime.

We can use the CSharpCodeProvider to do exactly this, it can compile some code, create an assembly (in my case in-memory) and then allow us to instantiate the code within that assembly. Let’s jump straight into some code and then we’ll look at how the code works

var param = new CompilerParameters
{
   GenerateExecutable = false,
   IncludeDebugInformation = false,
   GenerateInMemory = true
};
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Xml.dll");
param.ReferencedAssemblies.Add("System.Data.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.ReferencedAssemblies.Add("System.Xml.Linq.dll");

var codeProvider = new CSharpCodeProvider();
var results = codeProvider.CompileAssemblyFromFile(param, filename);

if (results.Errors.HasErrors)
{
   foreach (var error in results.Errors)
   {
      Console.WriteLine(error);
   }
}
else
{
   object o = results.
               CompiledAssembly.
               CreateInstance(typeName);
}

In the code above, we’re assuming that the source code we want to compile exists in a seperate C# source code file stored in the variable filename.

Firstly we create the CompilerParameters. I don’t want an executable to be generated and debug information will be of little use to me. I’m going to create the resultant assembly in memory as we’re not intending to write this to disc.

Next up we need to tell the compiler what assemblies will be required, ofcourse this might be best supplied in some alternate way, such as the script itself could be parsed or we might have another file with the assemblies listed, but for my purposes I’ll just list the “standard” assemblies.

We create a CSharpCodeProvider (as we’re working in C#) and passing the compiler parameters and the source code filename we get the code provider to compile the code. If any errors occur we simply list them (in this example, to the console).

Assuming all compiles we use the CompiledAssembly and create an instance of the type we’re interested in. In my example I supplied the typeName (i.e. class name) in the command line arguments to the application which uses obviously allows this code to be a little more flexible.

Once we’ve got the instance of the type we can obviously start interacting with it.