IT:AD:BAT

Summary

A lost art…

I'd suggest that if you're creating .BAT files for deployment purposes when IT:AD:Powershell is the proper way to do things – that' you're being lazy. Do it right.

That admonition out of the way, there's still a (rare) need to figure out what an old script file is doing – or patch one up.

Here are some notes to help understand an existing script, or patch it up:

Arguments

%* for everything.
%0 - the command used to call the batch file (could be foo, ..\foo, c:\bats\foo, etc.)
%1 is the first command line parameter, 
%2 is the second command line parameter,
and so on till %9 (and SHIFT can be used for those after the 9th).

%~nx0 - the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0 - drive and path to the script (d:\scripts)
%~dpnx0 - is the fully qualified path name of the script (d:\scripts\some-batch.bat)
String handing
 SET _test=123456789abcdef0
 
 SET _result=%_test:~0,5%
 Result: 12345

 SET _result=%_test:~7,5%
 Result: 89abc

 SET _result=%_test:~7%
 Result: 89abcdef0

File Handling

   
  #change to a directory
  cd 
  ## List files in a dir
  dir
  dir folder1\*.doc > output.txt
  ## rename a file
  ren file1 file2
  ren *.txt *.doc
  ## moving files
  move /y folder1\*.mp3 folder\
  ## make a dir
  mk newfolder3\sub1\sub2
  ## remove a dir
  rd folder1
  rd /s folder1   # sub folders
  rd /s /q folder1  #sub and quiet
  ## change attribtues
  attrib -r -s -h somefile
  attrib +r +s +h somefile

Flow Control

 //Case sensititive comparison:
 if %somevar% EQU "Foo" SET othervar="Bar"
 
 //Case insensitive comparison:
 if /i %somevar% EQU "Foo" SET othervar="Bar"
  

So:

   if /i %somevar% EQU "Foo" SET othervar="Bar" (
   echo ERROR: not so good...
   goto :shortusage
   )

Permissions

Check if user is admin

@rem ============================================================
@rem PRECHECK: is user is a Member has Admin Rights
@rem Note that this not the same check that user has started in Admin rights.
:checkisuseradmin
set admin=N
set domain=%USERDOMAIN%\
if /i "%domain%" EQU "%computername%\" set domain=
set user=%domain%%username%
for /f "Tokens=*" %%a in ('net localgroup administrators^|find /i "%user%"') do set admin=Y
@rem Then just test the value of %admin%
echo User is Local Admin:%admin%
if "%admin%" EQU "N" (
    echo ============================================================
    echo.
    echo ERROR: User must be a member of Local Admin
    echo.
    goto :usage
)

Check if user is running in admin console

@rem ============================================================
@rem PRECHECK: is user has started in admin mode
:checkisconsoleadmin
NET SESSION >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
    echo ============================================================
    echo.
    echo ERROR: Batch must be started from Console in Admin Mode.
    echo.
    goto :usage
)
echo Batch being run in Admin Console: Y