0

I'm trying to stop remote powershell job gracefully by using event. There are some good examples to do this with powershell cmdlets (e.g. this one).

But I don't know how to do the same thing from my custom cmdlet in C# code.

My solution is like following:

  1. Invoke CustomCmdlet as job in remote machine:

    Invoke-Command -Session $sess -AsJob -ScriptBlock { CustomCmdlet }

  2. Inside my CustomCmdlet C# code

     protected override void ProcessRecord()
     {
         // Question: How to write the C# code for following cmdlet? How to set my CancelJob function in the Action parameter?
         // Register-EngineEvent -SourceIdentifier MyEventSource -Action { CancelJob() }
    
         // Start a new task thread to run the real task
     }
    
     private void CancelJob()
     {
        // Get the event to cancel the job. 
        // Notify the task thread to clean up server resource and exit
     }
    
  3. When need to cancel the job, send an event to remote machine:

Invoke-Command -Session $sess -AsJob -ScriptBlock {New-Event -SourceIdentifier MyEventSource -MessageData "CancelTheJob" }

Thanks a lot!

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
supcxc
  • 11
  • 3

0 Answers0