Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a console-based process and apply a custom title using Powershell

I am converting an old cmd command to Powershell, and currently use:

START "My Title" Path/To/ConsoleApp.exe

This works as expected to launch ConsoleApp with My Title as it's window title. This has been replaced with Start-Process which works correctly, but does not provide a mechanism to change the title.

Is there another way to do this without resorting to using the cmd command?

like image 803
Ben Laan Avatar asked Jul 01 '10 04:07

Ben Laan


2 Answers

If you want to spawn a process with powershell with a custom title try:

$StartInfo = new-object System.Diagnostics.ProcessStartInfo
$StartInfo.FileName = "$pshome\powershell.exe"
$StartInfo.Arguments = "-NoExit -Command `$Host.UI.RawUI.WindowTitle=`'Your Title Here`'"
[System.Diagnostics.Process]::Start($StartInfo)

Note the backtick characters that escape the string for the title, they are vital!

like image 82
Lou O. Avatar answered Nov 03 '22 09:11

Lou O.


There is a small quirk when changing the text of the process' main window: if you try to change the text straight after you have started the process, it may fail due to one of many possible reasons (e.g. the handle to the control which displays the text does not exist at the time of the function call). So the solution is to use the WaitForInputIdle() method before trying to change the text:

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public static class Win32Api
{
    [DllImport("User32.dll", EntryPoint = "SetWindowText")]
    public static extern int SetWindowText(IntPtr hWnd, string text);
}
"@

$process = Start-Process -FilePath "notepad.exe" -PassThru
$process.WaitForInputIdle()
[Win32Api]::SetWindowText($process.MainWindowHandle, "My Custom Text")

Be aware that the application itself can still change the window text after you have made your own change.

like image 24
George Howarth Avatar answered Nov 03 '22 10:11

George Howarth