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
No comments:
Post a Comment