user2933845
user2933845

Reputation: 1

PowerShell: Command stops working once it's within a Start-Job block

I'm trying to write a script that will first display a messagebox, and then the script needs to proceed after a certain amount of time if the user doesn't click OK to the messagebox. The messagebox code works fine on its own, and then the code stops working once it's within a Start-Job block.

$job = Start-Job {

    $message = [System.Windows.Forms.MessageBox]::Show("Message body." , "Message title." , 0)

    if ($message -eq "OK" ) {Write-Host "User clicked OK."} 

}

$timeout = Wait-Job $job -Timeout 30

Stop-Job $job 

Receive-Job $job

Remove-Job $job

Error Message:

Unable to find type [System.Windows.Forms.MessageBox]: make sure that the assembly containing this type is loaded. + CategoryInfo : InvalidOperation: (System.Windows.Forms.MessageBox:String) [], RuntimeException + FullyQualifiedErrorId : TypeNotFound

Upvotes: 0

Views: 2666

Answers (1)

Keith Hill
Keith Hill

Reputation: 202092

In your scriptblock insert Add-Type -AssemblyName System.Windows.Forms at the beginning.

The job runs in a different PowerShell process so even though you had imported the WinForms assembly in your console, that assembly will not be imported in the new PowerShell session spun up by the job.

Upvotes: 2

Related Questions