Home > Software design >  Using Classes within an class
Using Classes within an class

Time:02-11

Using other classes with a class in Powershell

I have a question about working with classes in powershell, how does one use one class within another? For example I have the class 'SomeClass', I would like to declare that within the other class in the example class below.

Pseudo Code:

class SomeClass {
    [string] $Status
    [string] $Reason
}

class SomeMasterClass {
    [string] $ServerName
    [string] $FileName
    [SomeClass] $TheClass   # is this correct?
}

I am curious of this is the correct way to go about it or is there a better way?

CodePudding user response:

Here you have a reduced simple example of how you can have a class as property of another class, you're actually already doing it just need to add a bit more to it.

class SomeClass {
    [string] $Status
    [string] $Reason

    someClass () { }
    someClass ([hashtable]$Construct) {
        $this.Status = $Construct['Status']
        $this.Reason = $Construct['Reason']
    }
}

class SomeMasterClass {
    [string] $ServerName
    [string] $FileName
    [SomeClass] $TheClass

    someMasterClass () { }
    someMasterClass ([string]$Server, [string]$File, [someClass]$Class)
    {
        $this.ServerName = $Server
        $this.FileName   = $File
        $this.TheClass   = $Class
    }
}

$masterClass = [SomeMasterClass]::new(
    'Server01',
    'SomeFile',
    @{
        Status = 'OK!'
        Reason = 'Idk'
    }
)
PS /> $masterClass

ServerName FileName TheClass
---------- -------- --------
Server01   SomeFile SomeClass

PS /> $masterClass.TheClass

Status Reason
------ ------
OK!    Idk
  • Related