Search code examples
windowsbatch-filecmd

Change CMD title back to what it originally was (Batch)


I am trying to get my batch script to change the title of the Command Prompt to change back to what it was before my script started.

Here's an example:

@echo off
title My Script
REM rest of script here
:end
title %origcmdtitle%

So before it would run, it would have its default title; something like Command Prompt or C:\Windows\system32\cmd.exe

Then, when my script runs, the title changes to My Script

Finally, when the script ends, I want it to change back to the original title of CMD (it just stays as My Script)

Thanks!


Solution

  • This has always been one of many thorny issues with writing batch code.

    I've seen some fairly involved code to attempt to discern the current title and save the value in a variable so that the title could be restored before the batch script ends. But I have never been thoroughly satisfied with those results.

    I think the most robust and straight forward approach is to launch the script within a new cmd.exe session, where you can then set the title with impunity. Once your script ends, the child process will end, and the original cmd.exe process will resume control with the original title restored.

    You can have a script relaunch itself within a new cmd.exe session if you employ a "unique" extra parameter to signal that the relaunch has occurred. You can then use SHIFT to restore the original arguments.

    Here is a trivial example:

    @echo off
    if "%~1" equ ":SET-TITLE" goto %1
    cmd /c "%~f0" :SET-TITLE %*
    exit /b
    
    :SET-TITLE
    shift /1
    title myTitle
    echo %%1=%1  %%2=%2
    pause
    exit /b
    

    There are a couple potential problems with this method.

    • Any command line arguments are parsed multiple times, which could be problematic if there are escaped poison characters. The escapes would have to be doubled.

    • It is not possible for environment variable changes made by the script to survive after the script terminates, unless you write the variables to a file, and then reload the values from the file once you return to the parent session.