Search code examples
powershellvisual-studio-codewaitpowershell-core

PowerShell Start-Process -Wait does not wait for VS Code


In PowerShell Core, spawning VS Code like this, to start a diff/merge:

Start-Process -FilePath "$([System.Environment]::GetEnvironmentVariable('LOCALAPPDATA'))\\Programs\\Microsoft VS Code\\code.exe" -Wait -ArgumentList "-n --diff $FullFileNameSrcFrom $FullFileNameSrcTo"

works, but it does not wait. I think that's because code.exe starts child processes. If that's the case I could use -Passthru and do something like:

Get-Process *some criteria here* | ... and check if the children processes are finished

But: What could be the criteria?

I used procexp to try to find it out, but no success.

How can I identify the processes spawned by Code?

Maybe there is an easier way?

I use git with VS Code as my default commit editor and obviously git waits for VS Code to terminate before continuing - so "they" found a way to do this. Does that give me/you a hint?


Solution

  • Start-Process -Wait will also wait for child processes (Source):

    When using the Wait parameter, Start-Process waits for the process tree (the process and all its descendants) to exit before returning control. This is different than the behavior of the Wait-Process cmdlet, which only waits for the specified processes to exit.

    I don't know why, but waiting does not work for all processes. It does not even work for calc.exe, but it certainly works for some processes.

    There is a workaround for your problem with VS Code. It supports a wait option itself:

    -w or --wait Wait for the files to be closed before returning.

    You can do your diff/merge like this, where Start-Process will actually wait:

    Start-Process code -ArgumentList "-n -d -w .\test1.txt .\test2.txt" -Wait
    

    You do not even need Start-Process. This will also wait:

    code -n -d -w .\test1.txt .\test2.txt