Can I Change the Command Window Title When Running a Script?
Hey, Scripting Guy! When I run a batch file, I can use the Title command to change the caption of the command window. Can I change the caption of the command window from within a script?
— AA, Yokohama, Japan
Hey, AA. Well, yes, as long as you’re willing to open up a new command window. If you are, then you can use code similar to this:
Set objShell = CreateObject("Wscript.Shell") objShell.Run _ ("%comspec% /K title My Command Window |ping.exe 192.168.1.1"), _ 1, TRUE
Notice what we’ve done here. We’ve created an instance of the Wscript.Shell object, and then we’ve used the Run method to run Ping.exe. But see the big, long command string we used to run the script? What we’ve done is call %comspec% to open a new command window. We used the /K switch to ensure that the window remains open after the script finishes, and we’ve set the title of the window to My Command Window. That’s fairly straightforward.
The tricky part comes when we run Ping; we have to use the pipe separator (the | character) to essentially open a command window and run Ping all in one motion. What we’re saying here is, “Open a command window, set the window title, and run Ping.exe, all at the same time.” Without the piping, the script would open a command window titled My Command Window, but then open a second command window (with the default title) and run Ping in that second window. If you want to see what we’re talking about, try this:
Set objShell = CreateObject("Wscript.Shell") objShell.Run("%comspec% /K title My Command Window "), 1, TRUE objShell.Run("ping.exe 192.168.1.1"), 1, TRUE
By the way, if you want to get really fancy (or at least as fancy as the command shell allows you to get), you can change the foreground and background colors of the window at the same time you change the title. Dying to have light yellow text on a green background? Then run this script:
Set objShell = CreateObject("Wscript.Shell") objShell.Run _ ("%comspec% /T:2E /K title My Command Window|ping.exe " & _ "192.168.1.1"), 1, TRUE
The secret here is the mysterious little switch /T:2E, which enables you to change the foreground and background colors. For more information, open up a command window and type this: