简体   繁体   中英

How get the *original* cmd.exe console window title in PowerShell?

As soon as PowerShell start run in a cmd.exe window the title of the window is changed to "Windows PowerShell"; however, the original title is stored in some place, because when PowerShell terminates, the original window title is recovered.

I spent some time reviewing the related documentation, but most examples show how get the current window title or change it using $host.ui.rawui.WindowTitle , but there is not a single example on getting the original cmd.exe window title (perhaps I just don't know what terms include in this search).

Is there any way to get the original console window title before PowerShell start run?

Use next code snippet to get the original cmd console window title:

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

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!
  rem powershell -NoExit -Command $Host.UI.RawUI.WindowTitle='"!_myCmdTitle!"'
ENDLOCAL

Unfortunately, the powershell -NoExit -Command $Host.UI.RawUI.WindowTitle='"!_myCmdTitle!"' (commented up in above code snippet) workaround works only for simple titles not containing powershell sensitive characters like apostrophes, double quotes etc. For instance, next combination works with uncommented powershell line:

==> title some forgotten string
==> 39256629.bat

On the other hand, I didn't find proper escaping in case similar to this (BTW, your current question inspired my answer there)

==> TITLE ...but my title is complex, that's why I can't find proper escaping!!!
==> 39256629.bat

Powershell runs but keeps complaining for unexpected tokens tied to ... dots or ' apostrophes for different escaping attempts…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM