Just Code‎ > ‎

Powershell - Create new object of a custom Class using a Constructor

posted Nov 16, 2011, 5:35 AM by Peter Henell   [ updated Jan 25, 2012, 5:19 AM ]
The function NewExecutionResult is the constructor and inside it it specifies what fields that the new class should have.
function NewExecutionResult($testName, $numSucceded, $numFailed )
{
     $er = "" | Select TestName,NumSucceded,NumFailed
     $er.TestName = $testName
     $er.NumSucceded = $numSucceded
     $er.NumFailed = $numFailed
     
     $er = $er | Add-Member ScriptMethod GetName {$this.TestName} -passThru
     $er = $er | Add-Member ScriptMethod GetFailedTests {$this.NumFailed} -PassThru
     $er = $er | Add-Member ScriptMethod GetSuccededTests {$this.NumSucceded} -PassThru
     $er = $er | Add-Member ScriptMethod ToString { 
                 Write-Host ("Testname: " + $this.TestName )
                Write-Host ("Succeded: " + $this.NumSucceded )
                Write-Host ("Failed: " + $this.NumFailed )
                
            } -PassThru -Force
     $er
}


cls
$e  = NewExecutionResult "Peters test" 10 1

# Get the values using the mehods
$e.GetName()
$e.GetFailedTests()
$e.GetSuccededTests()

# Or by accessing the properties directly
$e.TestName
$e.NumFailed
$e.NumSucceded

$e.ToString()
Comments