Wednesday, January 18, 2012

Create Simple PowerShell Objects

I used to make Powershell objects the long and messy way. I would create an object and then use Add-Member to tack on NoteProperties and ScriptMethods. Even though I kept it organized, it was a lot to look at and people who were not as familiar with PowerShell were completely confused.

After finding the following method, I have completely refactored my Powershell objects for the larger scripts. It was actually pretty quick to do this and made the scripts much easier to read and therefore maintain.

First, the object is created as a New-Module. Also, notice that the switch -AsCustomObject is used when creating the module. Next, just declare your variables and functions like you would normally do. That last piece is to use the Export-ModuleMember cmdlet at the bottom of the module. Just use a * to tell it to export every variable and function.

You practically have a template that an be easily used to begin creating any object from existing sets of functions and the variables they need.

$test = New-Module {
[string]$teststring = "test successful"
function show {$teststring | Out-Host}
Export-ModuleMember -Variable * -Function *
} -AsCustomObject

Now that you have created your object, you can get/set the properties and run the methods in it.

$test.teststring
$test.teststring = "This object has a settable property."
$test.show()

Using this method chopped the lines in the scripts to less than half of what they were.

Enjoy!

PowerShell References