Tuesday, May 20, 2014

PowerShell Object Creation – New-Module Pt. 1


I have seen quite a few posts on creating custom objects in PowerShell, comparing it to techniques used in languages such as JavaScript but most use some variation of defining an object literal using Select-Object, New-Object, or a HashTable that is cast to PSCustomObject which are all fine and great ways of creating a one off Property Bag. These posts seem skip the most powerful way to define objects in PowerShell and that is to use the New-Module Cmdlet. The New-Module Cmdlet has a switch –AsCustomObject and a parameter –ScriptBlock that allow you to define a custom object. Inside the ScriptBlock every Variable defined is a property and you control whether it’s public or private by using the Export-ModuleMember Cmdlet if you export a variable it is public otherwise it is private. The most powerful part comes in the form that your functions defined inside the module ScriptBlock become the methods and the parameters define the methods arguments for the object and again the visibility is controlled by the Export-ModuleMember Cmdlet. The Functions can be Advanced Functions with Parameter Validation and Comment Based Help. Lets look at some code.



Running this code will provide us with a local variable $BlogPostInfo that we can inspect.



Example.001


We can see that the variable has the PSCustomObject type and are variable are now NoteProperties and our function is now a ScriptMethod. Also notice that our IsPublished variable is not included in the list because it is private, we did not export it. Next time we will cover some advanced topics such as defining ScriptProperties and method overriding.


$Until_Then = Good-Times | Get-Command

No comments:

Post a Comment