Wednesday, April 17, 2013

Unit testing a Powershell Commandlet

I chose to write Powershell commandlets in C#. I created a class library (DLL) project and inherited a class from Cmdlet base class. I created a snapin class derived from PSSnapIn to be able to install my commandlets from powershell.

Unit testing

Writing a unit test

    public class UnitTest1
        private static RunspaceConfiguration config;
        private static Runspace runspace;
        private static Pipeline pipe;
        private static Command command;

        public static void TestFixtureSetup(TestContext context)
            config = RunspaceConfiguration.Create();

            PSSnapInException warning;
            config.AddPSSnapIn("SnapinName", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);

        public static void TestFixtureTeardown()

        public void Setup()
            pipe = runspace.CreatePipeline();
            command = new Command("CommandName");

        public void TestMethod1()
            command.Parameters.Add(new CommandParameter("ParameterName", "Value"));

            var psObject = pipe.Invoke();

Snapin couldn't be found

I wrote a unit test against one of my commands but it couldn't find my snapin, I got the following exception:
System.Management.Automation.PSArgumentException: System.Management.Automation.PSArgumentException: The Windows PowerShell snap-in '...' is not installed on this computer..

I could use my snapin from Powershell command line.


Add the following lines as post-build events:
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe $(TargetPath)
c:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  $(TargetPath)

Both 32-bit and 64-bit installation will happen this way.


Visual Studio 2012 is a 32-bit process. I registered with 64-bit install util only. Now I register both versions.