0

I am trying to run netmon on a series of machines, I am able to start netmon, which appears to be fine. However when I issue a Stop-Job * it appears that netmon is not closing correctly, which causes the packet capture to be useless. Netmon is expecting a "ctrl + C" , is there a way to issue this when I am stopping the jobs? Netmon can use other key sequences using the /stopwhen /keypress option is used

$server = get-content C:\Server.txt 
$capturedevice = "CAPTUREMACHINE"

foreach ($server in $server)
{ $scriptBlockContent = { param ($servername)
Nmcap /capture /network * /file C:\temp\"$servername".chn:400MB } 
Invoke-Command -ComputerName $server -Scriptblock $scriptBlockContent -ArgumentList $server -AsJob }

foreach ($capturedevice in $capturedevice){ $scriptBlockContent = 
{ param ($capturedevicename) Nmcap /capture /network * /file D:\temp\"$capturedevicename".chn:400MB } 
Invoke-Command -ComputerName $capturedevice -Scriptblock $scriptBlockContent -ArgumentList $capturedevice -AsJob }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
james
  • 157
  • 1
  • 2
  • 11

1 Answers1

1

I don't have a ready solution for you, but here is some food for thought.

You have 2 issues to take care of:

  1. You need to gracefuly close Nmcap process, so it could save the capture file.

    1. You can try to go with Start-Process:

      $nmcap = Start-Process -FilePath "Nmcap" -ArgumentList  "/capture /network * /file C:\temp\"$servername".chn:400MB"
      
      $nmcap.Close() #or $nmcap.CloseMainWindow()
      $nmcap.WaitForExit()
      
    2. Or if code above wouldn't work using $nmcap.Close() or $nmcap.CloseMainWindow(), then you cloud try to send Ctrl+C to the Nmcap:

      $Wasp = Add-Type -MemberDefinition @'
      [DllImport("user32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool SetForegroundWindow(IntPtr hWnd);
      '@ -Passthru
      $null = Add-Type -Assembly System.Windows.Forms
      
      if($Wasp::SetForegroundWindow($nmcap.MainWindowHandle)) {
          [System.Windows.Forms.SendKeys]::SendWait("^C")
          $nmcap.WaitForExit()
      }
      
    3. If everything fails, you could try to adopt C# solution: Stopping command-line applications programatically with Ctrl-C event from .Net – a working demo
  2. To gracefuly close Nmcap process you have to detect inside the job when PowerShell tries to stop this job.

    1. File based approach: How To Gracefully Stop An Asynchronous Job In PowerShell
    2. Event-Based approach: Monitoring jobs in a PowerShell session from another PowerShell session. But you'd have to reverse the code and send signal to the job, I've not tried it, so I don't know if it's possible.
Community
  • 1
  • 1
beatcracker
  • 6,714
  • 1
  • 18
  • 41