How to get window title in windows from shell

Solution 1:

The script below shows that tasklist /v /FO:CSV does not truncate long window titles and independently solves two tasks:

  • Part 1 displays all useful window titles along with image names and PIDs in csv format; findstr is used to narrow down output to really useful titles.
  • Part 2 displays PID and title of the command prompt window where the script was executed from (my own cmd).

Script:

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

rem Part 1: ALL USEFUL WINDOW TITLES
echo(
set "_myExcludes=^\"conhost ^\"dwm ^\"nvxdsync ^\"nvvsvc ^\"dllhost ^\"taskhostex"
for /F "tokens=1,2,8,* delims=," %%G in ('
  tasklist /V /fo:csv ^| findstr /V "%_myExcludes%"
                                        ') do (
    if NOT "%%~J"=="N/A" echo %%G,%%~H,%%J
)

rem Part 2: MY OWN cmd WINDOW TITLE
echo(
set "_myTitleTail= - %~0"
for /F "tokens=1,2,8,* delims=," %%G in ('
  tasklist /V /fo:csv ^| findstr /I /C:"%_myTitleTail%"
                                        ') do (
    set "_myTitleBatch=%%~J"
    set "_myCmdPIDno=%%~H"
)
call set "_myCmdTitle=%%_myTitleBatch:%_myTitleTail%=%%"
echo _myCmdPIDno=%_myCmdPIDno%
SETLOCAL EnableDelayedExpansion
  echo _myCmdTitle=!_myCmdTitle!
ENDLOCAL

Output:

==> TITLE ...but my title is very, very long, that's why I receive only partial title. Also 
I was thinking about wmic utility, but can't find desired flag!!!

==> .\SU\378790.bat

"Image Name",PID,"Window Title"
"VDeck.exe",4032,"VIA HD Audio Deck"
"chrome.exe",5760,"How to get window title in windows from shell - Super User - Google Chrom
e"
"powershell_ise.exe",5568,"Windows PowerShell ISE"
"cmd.exe",4980,"...but my title is very, very long, that's why I receive only partial title.
 Also I was thinking about wmic utility, but can't find desired flag!!! - .\SU\378790.bat"
"PSPad.exe",5108,"378790.bat"
"cmd.exe",3888,"d:\bat"
"cmd.exe",5648,"Administrator: Command Prompt"

_myCmdPIDno=4980
_myCmdTitle=...but my title is very, very long, that's why I receive only partial title. Als
o I was thinking about wmic utility, but can't find desired flag!!!

==>

Resources (required reading):

  • (command reference) An A-Z Index of the Windows CMD command line
  • (helpful particularities) Windows CMD Shell Command Line Syntax
  • (%~G etc. special page) Command Line arguments (Parameters)
  • (special page) EnableDelayedExpansion
  • (SET %variable:StrToFind=NewStr%) Variable Edit/Replace

Solution 2:

AutoHotkey can help you achieve this. Let's write a script that outputs the process and titles of all open windows to stdout:

WinGet, windows, list

Loop, %windows%
{
    id := windows%A_Index%
    WinGet, process, ProcessName, ahk_id %id%
    WinGetTitle, title, ahk_id %id%
    FileAppend, %process% %title%`n, *
}

ExitApp

Compile the script to get a portable .exe.

Now, we can run the following from the Windows command line:

MyScript.exe | more

Example:

screenshot