PowerShell: CPM – New Parameter Object

In the intro I discussed my need to manage all script parameters centrally. To do this I want to create a PowerShell module to manage the parameters and to store the data in the SQL table I created in my previous article.

Now lets create a new object-type!

Creating a new object-type

PowerShell is an object-oriented scripting language. When making a new module you often want to use your own custom object.
I want to use a custom parameter-object that has the same basic properties that I used to define the SQL table:

  • Name: The actual name to be used in scripts
  • Value: The value to be linked to the name
  • Description: A description so everyone knows what the parameter is for

There are several ways to define a new object type in PowerShell.
I will be using the Add-Type cmdlet in conjunction with a class definition in C#.

First I will define the new object SParameter in my custom namespace SManagement.
I put an “S” in front of all objects I create so I can distinguish between the objects I created myself and those I haven’t.
I chose “S” because it is the first letter of my company’s name.
Each basic properties, as defined in the SQL table, is also defined in the SParameter-object.

namespace SManagement
{
    public class SParameter
    {
        private string name;
        private string value;
        private string description;

        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
        public string Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
        public string Description
        {
            get { return description; }
            set { description = value; }
        }
    }
}

You can’t use the shortened properties definition { get; set; } when using the .cs-file in PowerShell.

Once you created the SParameter.cs file you should add the types you define in it to your PowerShell-script so you can use them.
Place the .cs-file in the same directory as your script and add the following line to the start of your script or module-file:

Add-Type -Path "$PSScriptRoot\SParameter.cs"

now the object type [SManagement.SParameter] and al its properties are usable within your script.

SQL Connection

Now that we have an object-type to work with, let’s get a connection to our data.
Next step: SQL Connection

Advertisements

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: