Search code examples
c#multithreadingpowershellpowershell-remoting

Remote Powershell code blocks execute in parallel


Could somebody help with understanding multithreading in remote powershell? I am trying to copy a file to remote computer using only WinRM. Here is the algorithm:

  1. Divide local file to byte[] chunks.
  2. Every chunk is base64 encoded.
  3. base64 string sent to remote WinRM in a powershell code block, which decodes it and appends to file.
  4. Remote file eventually filled with all bytes and is an exact copy of local file.

The problem is that I get "The process cannot access the file, because it is used by another process" type of errors when executing remote powershell blocks. It looks like powershell executes my script blocks in parallel. But I need sequential execution. Can I override this?

Full code example is available here.


Solution

  • Each time you create a remote PowerShell session, it is using a different PowerShell process to execute the request. This is why you are running into file contention issues. You should consider using the same remote session for each operation rather than creating a new one each time you want to append a chunk.

    BTW if you are on (or when you get to) V5, you can use $s = New-PSSession remoteComputerName; Copy-Item src.txt C:\dst.txt -ToSession $s to copy a file to a remote computer.