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.