Search code examples
powershellclassjobs

How to call a class object in powershell jobs


I have created test PowerShell class. My plan is to run parallels background jobs to create class objects and execute methods in the class

class Test {

    [String]$ComputerName
    
    
    [String]TestMrParameter() {

        if ($this.ComputerName -eq 'jhon'){throw "Bad thing happened"}
        
        return $this.ComputerName 

    }
}

$names = @('david', 'jhon', 'mark','tent')
$jobs = [System.Collections.ArrayList]@()

function TestMrParameter2 {
    param (
        [String]$name
    )
    [Test]$obj = [Test]::new()
    $obj.ComputerName = $name
    Write-Host $name + "TestMrParameter2 Function Reached!!!"
    $output=$obj.TestMrParameter()
    Write-Host "Output of the Test class is" + $output
}


foreach ($name in $names) {

    $out = Start-Job -ScriptBlock ${Function:TestMrParameter2} -ArgumentList $name
    $jobs.Add($out) | out-null

}

I get my jobs as completed but not with my expectations. Therefore, I checked each job details to get more insights and I found this error on each job. It cannot identify the class to create the object out of it.

Unable to find type [Test].
    + CategoryInfo          : InvalidOperation: (Test:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound
    + PSComputerName        : localhost
 
The property 'ComputerName' cannot be found on this object. Verify that the property exists and can 
be set.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound
    + PSComputerName        : localhost

Solution

  • This has been answered already on here:

    How do I Start a job of a function i just defined?

    via the initialisation script switch. Either that, or put your class function in the Job script itself.