Search code examples
powershellconsole.net-6.0title

How to change the console window title of a dotnet application run by powershell?


I'm launching multiple dotnet run commands using a Powershell script.

$projectsRootDirectory = "$PSScriptRoot\.."

Start-Process -FilePath 'dotnet' `
              -WorkingDirectory "$projectsRootDirectory\SomeProjectFolder" `
              -ArgumentList 'run --launch-profile My.Profile --debug'

When I launch 6 of them simultaneously I have a problem distinguishing which one is which.

From questions like this one, I learned it is possible with the -c parameter:

Start-Process powershell '-c "$host.UI.RawUI.WindowTitle = \"Speed Test\"; .\SpeedTest.ps1"'

But as far as I understand, the -c parameter is for the powershell command. Can I achieve the same with dotnet run command?


Solution

  • In your case, the simplest solution is to call cmd.exe's CLI in order to call its internal start command, which is comparable to Start-Process while allowing you to set the console window title directly:

    $projectsRootDirectory = "$PSScriptRoot\.."
    
    cmd /c @"
    start /d "$projectsRootDirectory\SomeProjectFolder" "Speed Test" dotnet run --launch-profile My.Profile --debug
    "@
    
    • Note the use of a here-string to make use of embedded quoting easier.

    • Following any of it owns options - such as /d to set the working directory for the new process - start interprets an immediately following "..."-enclosed argument as the title for the new console window with all remaining arguments constituting the executable to start plus any arguments.

      • Note that options such as /d must come before a window title / the executable plus arguments to start.
    • Start-Process, by contrast, does not support setting a console window title for applications, so the only way to do that is to have the newly launched process itself change the title; if that process is also a shell (cmd.exe or the PowerShell CLI, powershell.exe / pwsh.exe), you can use the latter's features to do that (title Speed Tests or [Console]::Title = 'Speed Test').
      While you could use this technique to indirectly launch the target executable, the above technique is simpler.