Wait for remote process to finish

I have following sample code:

$Domain = "Enter computer name here"
$RemoteCredential = Get-Credential -Message "Credentials are required to access '$Domain'"
$CimServer = New-CimSession -ComputerName $Domain -Credential $RemoteCredential

# Save netstat output to C:\ on remote computer, this command never ends btw.
[string] $cmd = "cmd /c c:\windows\system32\netstat.exe 5 >> \\$Domain\C$\netstat.txt"

# Invoke netstat command remotely
Invoke-CimMethod -ClassName Win32_Process -MethodName Create `
      -Arguments @{ CommandLine = $cmd } -CimSession $CimServer | Out-Null

# Wait for netstat command to finish
Invoke-Command -ComputerName $Domain -Credential $RemoteCredential -ScriptBlock {
       $ID = Get-Process -Name netstat.exe | Select-Object -ExpandProperty Id

       Write-Verbose -Message "Waiting process $ID to finish" -Verbose
       Wait-Process -Id $ID

Problem occurs in last command where I want to wait for netstat to finish before doing anything else.
Issue is that Get-Process does not return anything and therefore process ID is unknonwn.

Another issue is I can’t use return value of Invoke-CimMethod to obtain process ID, return value is PSCustomObject that looks like this:

ProcessId  ReturnValue  PSComputerName
---------  -----------  ---------------
       776           0           VM-PRO

Problem here is that ProcessId value does not match the actual process ID on remote computer.
I don’t know why is that?

Do you have any solution on how to obtain real process ID for the command above to wait for it?

Note: If you want to test this code you’ll need PS remoting enabled on remote computer such as virtual machine with external virtual switch.

I figured out following works:

Invoke-Command -ComputerName $Domain -Credential $RemoteCredential -ScriptBlock {
	Get-Process -Name "netstat" -ErrorAction SilentlyContinue | Wait-Process

But still, I don’t understand why output of Invoke-CimMethod contains an invalid process ID?

hi, have a look at this thread, i was just solving the same problem, maybe something will help you

1 Like

Thank you for sharing, I’m glad to see not to be the only one having this question.

hi did this help you? write your solution

Would adding Start-Sleep -Seconds help at the end of the script?

     Write-Verbose -Message "Waiting process $ID to finish" -Verbose
       Start-Sleep -Seconds 120

I already have a solution which I posted, but remaining question is about Invoke-CimMethod.
Your thread says nothing about Invoke-CimMethod issues I’m having.

I’ve read it and the solution to pipe Wait-Process is to pipe output to it.