powershellwindows-terminal

The result of opening multiple panes in Windows Terminal via ps1 script is unpredictable


I made a pretty simple PowerShell script to run my project.

$path = './Desktop/Code/projects'
$windowId = 'app'
$wtCommand = 'split-pane'

$command = "wt -M -w $windowId pwsh -NoExit -c 'cd $path/app/client && npm run dev' && " +
           "wt -M -w $windowId $wtCommand -V pwsh -NoExit -c 'cd $path/app/backend && air' && " +
           "wt -M -w $windowId $wtCommand -V pwsh -NoExit -c 'cd $path/app/admin && npm run dev' && " +
           "wt -M -w $windowId $wtCommand -H pwsh -NoExit -c 'cd $path/Auth/server && air' && " +
           "wt -M -w $windowId $wtCommand -V pwsh -NoExit -c 'cd $path/service_1 && air' && " +
           "wt -M -w $windowId $wtCommand -V pwsh -NoExit -c 'cd $path/service_2 && docker run -p 8090:8090 service_2:latest'"

Invoke-Expression $command

And it ALWAYS opens exactly two tabs, but sometimes it opens all the panes correctly, sometimes don't split the editor at all, running just random two apps. Really random behavior.

But if I change command to the new-tab instead of the split-pane, it will open all the 6 tabs every time just fine.

The terminal version is 1.19.10302.0. I've tried pre-release too, same there.


Solution

  • I suspect that launching multiple wt.exe instances, as you've tried - each of which launches asynchronously - can lead to race conditions.

    You can avoid the problem - while also speeding up the operation - if you use a single wt.exe call and pass it all subcommands at once, separated with ;:

    $path = './Desktop/Code/projects'
    $windowId = 'app'
    $wtCommand = 'split-pane'
    
    wt -M -w $windowId pwsh -NoExit -c "cd $path/app/client && npm run dev" `; `
             $wtCommand -V pwsh -NoExit -c "cd $path/app/backend && air" `; `
             $wtCommand -V pwsh -NoExit -c "cd $path/app/admin && npm run dev" `; `
             $wtCommand -H pwsh -NoExit -c "cd $path/Auth/server && air" `; `
             $wtCommand -V pwsh -NoExit -c "cd $path/service_1 && air" `; `
             $wtCommand -V pwsh -NoExit -c "cd $path/service_2 && docker run -p 8090:8090 service_2:latest"
    

    Note: