Wednesday, February 9, 2011

Check for Caps-Lock in Batch Script

For years, I've had to access restricted network shares, most often when logged on with either local-computer credentials, or as an end-user who doesn't have permission to access the share. So I fire off a script that passes my credentials.

It really sucks when they have caps-lock on, and I don't know it, and lock myself out. Scripts are good about doing that. Since a script can store your credentials and pass it to several different shares, you can get locked out in a split second. You don't have to type your password wrong manually three times.

With 32-bit Windows, there is an old 16-bit executable that can check this. It's called debug.exe, and Microsoft stores it in the wrong place (they do that a lot).
C:\Windows\system is supposed to hold legacy 16-bit files. C:\Windows\System32 holds 32-bit files. So guess where they stuck it? They stuck the 16-bit debug into System32. (It's the Microsoft way.)
Debug.exe won't function on a 64-bit computer, no matter how you try to trick WOW (Windows-On-Windows) into handling it.

Copy the code below and save it in a text file and name it anything ending in .bat or .cmd. Then fire it off with caps-lock either on or off to see the difference.
I've tried it successfully on Windows XP and Windows 7 32-bit. (Beware line-wrapping.)


TITLE DOMAINAPPS tech-share
echo off

:: Check for caps-lock on...
set capslock=0
for /f "skip=1 tokens=2" %%a in ('(echo d0:417,417 ^&echo q^) ^|debug') do IF %%a GEQ 40 SET capslock=1
if %capslock% == 1 cls&echo.& echo CAPSLOCK IS ON!!& color cf& echo.& pause

:: Prompt for username...
cls&echo.&color 1f
set /p useris=Type Your Username:

:: Now pass your credentials...
color 9f
net use \\OurDomain.net\DOMAINAPPS /user:%useris%OurDomain.net
:: And open the share...
explorer \\OurDomain.net\DOMAINAPPS


For x64 Windows, I resort to using Powershell instead of debug.exe. This has the added advantage of working on both 32-bit and 64-bit.
The following code should work, even if a bit slower. (Note that I like to leave Powershell script security on "Restricted", and drop it just-in-time for my command, then raise security back up immediately afterward.)


TITLE DOMAINAPPS tech-share
echo off

:: Check for caps-lock on...
set capslock=0
powershell -command "& {Set-ExecutionPolicy Unrestricted -force}"
for /f "tokens=*" %%a in ('powershell -command [console]::CapsLock') do set capslock=%%a
:: Return the security policy to default, restricted.
powershell -command "& {Set-ExecutionPolicy Restricted -force}"
if %capslock% == 1 cls&echo.& echo CAPSLOCK IS ON!!& color cf& echo.& pause

:: Prompt for username...
cls&echo.&color 1f
set /p useris=Type Your Username:

:: Now pass your credentials...
color 9f
net use \\OurDomain.net\DOMAINAPPS /user:%useris%OurDomain.net
:: And open the share...
explorer \\OurDomain.net\DOMAINAPPS

No comments:

Post a Comment