How to Create an Object in PowerShell

PowerShell Team

Today someone in Xbox Live Operations (the folks that keep xBox Live alive and well) pinged me with a simple question about PowerShell with a complicated answer: “How do I create a class in PowerShell?”

There’s two scenarios I find where people want classes.  The first (and most common) is familiarity: the person wants to make a class in PowerShell because they think of problems in terms of classes.  The second is practical: the person wants to make a collection of properties and methods, because that’s what the pipeline in PowerShell plays nicely with (for instance, you can Group, Sort, or Select easily on properties on an object, but not as easily on a hashtable).

There are three ways you can do this with PowerShell V2 that I know of.  You can using Add-Type to compile C# or other .NET languages directly, and this is the only way you can make a real class definition in PowerShell V2.  You can also use New-Module with -asCustomObject to export the functions and variables within a dynamic module as a custom object, but you should be aware that complicated parameter sets do not work well as script methods.  Finally, you can do things the old V1 way, which is by tacking properties and methods onto an object with the Add-Member cmdlet.  Here’s the same object, built in 3 different ways:

# You can compile a class with C# or other .NET languages in PowerShell v2
Add-Type @'
public class MyObject
    public int MyField = 5;
    public int xTimesMyField(int x) {
        return x * MyField;
$object = New-Object MyObject
# You can also use -asCustomObject with the New-Module cmdlet to export a module as a class
$object = New-Module {
    [int]$myField = 5
    function XTimesMyField($x) {
        $x * $myField
    Export-ModuleMember -Variable * -Function *
} -asCustomObject
# You can also simply declare an object and start tacking on properties and methods with the
# Add-Member cmdlet.  If you use -passThru you can make one giant pipeline that adds all of the
# members and assign it to a variable
$object = New-Object Object |
    Add-Member NoteProperty MyField 5 -PassThru |
    Add-Member ScriptMethod xTimesMyField {
        $x * $this.MyField
        } -PassThru

Hope this Helps

James Brundage [MSFT]


Discussion is closed.

Feedback usabilla icon