A PowerShell Conversion Challenge

PowerShell’s flexibility and raw power stem from a fundamental concept of working with objects in a pipeline. Experienced PowerShell scripters and toolmakers should be experienced in creating custom objects, including using PowerShell classes. The first challenge of 2021 is predicated on this skill set.

The idea behind this challenge is that you are writing a new PowerShell tool that will generate a custom object based on an existing object in PowerShell like a service or volume. This new tool will use a PowerShell class to define the object. Your challenge is not to write the tool, but rather create a tool that will take an existing object and create the corresponding class definition.

The design principal is that a PowerShell scripter can take an instance of an object, like a System.ServiceProcess.ServiceController, and create a PowerShell class definition, copying selected properties such as Name and State. The new class definition should focus on properties, although you can insert placeholder text for methods. Your conversion tool should work from the pipeline and allow the user to specify a new class name.

You should end up with a result similar to this.

# this class is derived from System.ServiceProcess.ServiceController
class MySvc {
    #properties
    [System.String]$Name
    [System.String]$DisplayName
    [System.String]$MachineName
    [System.ServiceProcess.ServiceControllerStatus]$Status
    [System.ServiceProcess.ServiceStartMode]$StartType
    #Methods can be inserted here
    <#
    [returntype] MethodName(<parameters>) {
        code
        return value
    }
    #>
    #constructor placeholder
    MySvc() {
        #insert code here
    }
} #close class definition

This is merely one possible output. Your result can be as simple or as complex as you want.

Bonus items:

  • Allow the user to include or exclude properties
  • Include a placeholder for a constructor
  • Let the user specify a constructor
  • Let the user specify a method
  • Be VSCode aware and insert the new class automatically into the current file
  • Support cross-platform

You are encouraged to be creative. Your solution may be more than one command. It may rely on JSON or psd1 files. Your solution should work in both Windows PowerShell 5.1 and PowerShell 7.x.

The Chairman looks forward to seeing links to your work in the comments.


8 Replies to “A PowerShell Conversion Challenge”

  1. thedavecarroll

    I finally managed to find/make the time to work on this challenge. I believe my code satisfies 7 out of 10 of the requirements. I’ve written an article, apparently part 1, that takes a look into my process.

    I will be continuing work on it as it will help me with the classes for BluebirdPS (once I get it to be recursive, PascalCasing of properties, and type detection).

    https://powershell.anovelidea.org/powershell/creating-class-definition-from-object-part-1/

Comments are closed.