Batch Script Add Windows Users using Netsh

The following batch script will add a group of users to Windows, set no password, and require a password change at first logon.

@echo off
setlocal enabledelayedexpansion

set user1=John Q. Smith
set user2=Jane Doe
set user3=Joe Montana
set user4=Alicia Silverstone

set users=(user1 user2 user3 user4 user5 user6)

for %%u in %users% do (
  echo net user %%u /logonpasswordchg:yes /fullname:"!%%u!" /add
)

Batch Script to get Disk Usage of Folders Recursively

Rob van der Woude has a nice batch script to get disk usage of folders & subfolders in Windows since there isn’t a built-in function.  This could be similar to Linux du command.

 

@ECHO OFF
:: Use local variables
IF "%OS%"=="Windows_NT" SETLOCAL

:: Check command line arguments and Windows version
ECHO.%1 | FIND "/" >NUL
IF NOT ERRORLEVEL 1 IF /I NOT "%~1"=="/L" GOTO Syntax
ECHO.%1 | FIND "?" >NUL
IF NOT ERRORLEVEL 1 GOTO Syntax
ECHO.%1 | FIND "*" >NUL
IF NOT ERRORLEVEL 1 GOTO Syntax
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
IF NOT "%~1"=="" IF /I NOT "%~1"=="/L" IF NOT EXIST "%~1" GOTO Syntax
SET LongFormat=1
IF /I NOT "%~1"=="/L" IF /I NOT "%~2"=="/L" SET LongFormat=0

:: Go to start directory
SET StartDir=%CD%
IF NOT "%~1"=="" IF /I NOT "%~1"=="/L" SET StartDir=%~1
PUSHD "%StartDir%"
IF ERRORLEVEL 1 GOTO Syntax

:: Display header
ECHO Directory	Space used (MB)
ECHO.=========	===============

:: Display disk usage for start directory
IF NOT EXIST *.* GOTO SubDirs
FOR /F "tokens=3,4*" %%A IN ('DIR %1 /A-D /-C ^| FIND /I "File(s)"') DO SET ListDir=%%A
:: Different procedures depending on /L switch
IF "%LongFormat%"=="1" GOTO LongFormat
SET /A ListDir=%ListDir%+524288
SET /A ListDir=%ListDir%/1048576
ECHO..	%ListDir%
SET ListDir=
GOTO SubDirs
:LongFormat
:: Strip last 6 digits from value
SET ListDir=%ListDir:~0,-6%
IF NOT DEFINED ListDir SET ListDir=0
:: Display resulting value in MB
ECHO..	%ListDir%
:: Clear variable
SET ListDir=


:: Display disk usage for every subdirectory
:SubDirs
FOR /D %%A IN (*.*) DO CALL :List%LongFormat% "%%~A"

:: Done
POPD
GOTO End


:List0
:: Set variable value to bytes used by directory
FOR /F "tokens=3,4*" %%B IN ('DIR /A /-C /S "%~1" ^| FIND /I "File(s)"') DO SET ListDir=%%~B
:: Add 0.5MB in order to properly round the value when integer divided by 1MB
SET /A ListDir=%ListDir%+524288
:: Integer divide by 1MB
SET /A ListDir=%ListDir%/1048576
:: Display resulting value in MB
ECHO.%~1	%ListDir%
:: Clear variable
SET ListDir=
GOTO:EOF


:List1
:: Set variable value to bytes used by directory
FOR /F "tokens=3,4*" %%B IN ('DIR /A /-C /S "%~1" ^| FIND /I "File(s)"') DO SET ListDir=%%~B
:: Strip last 6 digits from value
SET ListDir=%ListDir:~0,-6%
IF NOT DEFINED ListDir SET ListDir=0
:: Display resulting value in MB
ECHO.%~1	%ListDir%
:: Clear variable
SET ListDir=
GOTO:EOF


:Syntax
ECHO.
ECHO DiskUse, Version 5.01 for Windows 2000 / XP
ECHO Display disk space used by subdirectories (tab delimited)
ECHO.
ECHO Usage:  DISKUSE  [ startdir ]  [ /L ]
ECHO.
ECHO Where:  "startdir"  is the directory containing subdirectories to be
ECHO                     inventoried (default is the current directory)
ECHO         "/L"        is used for large numbers, over 2GB, to prevent return
ECHO                     of negative numbers due to batch math limitations
ECHO                     (integer division by 1000000 instead of properly
ECHO                     rounded mathematical division by 1048576)
ECHO.
ECHO Written by Rob van der Woude
ECHO http://www.robvanderwoude.com

:End
IF "%OS%"=="Windows_NT" ENDLOCAL

Batch File to Cleanup Windows 2000, XP and Server 2003 User Profiles, Temp Folders, Internet Explorer Temporary Files

I’ve had this around for the longest time and figured I better put it here before I lose it forever to the dying Microsoft releases.

Note: This also cleans up VMware temporary files which build up over time. See this post for more information:  VMware Tray Dump Files Chewing up Space

Update: Added line to remove Temporary Internet Files directory/subdirectories also.

@echo off
setlocal

@for /d %%d in ( C:Documents and Settings* ) do @(
  echo %%d
  if exist %%dApplication DataVMware (
    del /q %%dApplication DataVMware*.*
  )
  if exist %%dLocal Settings (
    if exist %%dLocal SettingsTemp (
      for /d %%e in ( %%dLocal SettingsTemp* ) do @(
        attrib -R -A -S -H %%e*.*
        rmdir %%e /s /q
      )

      if exist %%dLocal SettingsTemporary Internet Files (
        rmdir %%dLocal SettingsTemporary Internet Files /s /q
      )

      if exist %%dLocal SettingsTemp*.* (
        attrib -R -A -S -H %%dLocal SettingsTemp*.*
        del %%dLocal SettingsTemp*.* /q
      )
    )
  )
)

Batch Rename Files and/or Folders in Windows Command Line

Batch rename files using Windows command line.

for /d /r %x in ("*") do pushd "%x" && ren *.eml *.msg && popd

Recently restored about 18k emails in various folders from a PST file which exports as an .MSG formatted file. I then reconverted those .MSG to .EML format. Now, the mail server I’m using requires .MSG extension but .EML format (go figure) so I had to rename all these suckers.

Easiest way was with some command line kung-fu. Luckily the ren *.eml *.msg works otherwise this would have been a bit more complicated.

I also had to rename all the folders and append .IMAP; this was accomplished easiest with:

for /d /r %x in ("*") do ren "%x" "%~nx.IMAP"

DOS Batch Date String Manipulation

Why do people make this so hard?  I see huge scripts on the internet dedicated to just this topic of parsing the date.  Here, it’s this simple:

First, let’s look what date looks like in DOS:

C:UsersAdmin>date /t
Tue 06/12/2012

With that in mind, you can also use the built-in %DATE% variable:

C:UsersAdmin>echo %DATE%
Tue 06/12/2012

Now that we have this information, let’s look at how to simplify this and come up with whatever format we want to display the date in…

C:UsersAdmin>echo %date:~-4,4%%date:~-7,2%%date:~-10,2%
20121206

String substitution; Read more about it here: DosTips

So you have replaced something like this:

@For /F tokens=1,2,3 delims=.  %%A in ('Date /t') do @(
Set Day=%%A
Set Month=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year% 

With a single, simple, line!

If you want to experiment further, try using %TIME% too. I use %DATE% and %TIME% in my backup/compression batch scripts for pre/post backup solutions in many cases and also for log files. Works like a champ.

Parse CSV with Batch Script

Here’s a basic method of parsing a CSV file using Microsoft Batch.

The following code will allow me to use all the CSV fields. Let’s suppose the CSV contains the following:

Example CSV

Name, Email, Username, Password
John Doe,jdoe@example.com,jdoe123,secretpassword
Jane Doe,janebug@example.com,janeybug1,topsecret

Batch Script

@echo off
setlocal
for /F usebackq tokens=* delims=, %%a in (c:tempusers.csv) do (
echo Name:  %%a
echo Email:  %%b
echo Username:  %%c
echo Password:  %%d
)

Output from Batch

Name:  John Doe
Email:  jdoe@example.com
Username:  jdoe123
Password:  secretpassword
Name:  Jane Doe
Email:  janebug@example.com
Username:  janeybug1
Password:  topsecret

[stextbox id=info caption=Note]If the CSV file you are working with uses quotes also, then when using the variable, specify %%~a to strip the quotes from the variable. See help for[/stextbox]

If you are only interested in a few columns, you could use the following for the tokens= specifier in the for loop.

tokens=3,4

That will only return the 3rd and 4th result based on the , delimiter and in this case it is the username and password. You still use %%a then %%b for your variables.

Get CPU Usage of a Process from Command Line

Here’s some kung-fu command-line that I hacked up this morning while brainstorming a few issues I had come across.

Basically, I needed to figure out how to keep an eye on a particular process’ CPU time. Sure, you can watch this from Task Manager but this method is better (IMHO) because I can save the log output for future analysis.

For example, I can launch my program and then start this batch file to monitor it’s CPU time throughout it’s life. When the process terminates, the batch file terminates as well.

Here’s the batch file code:

@echo off
: report processor time for given process until process exits (could be expanded to use a PID to be more
: precise)
:
: Usage:  foo.cmd <processname>

set process=%~1
echo Press CTRL-C To Stop...
:begin
for /f tokens=2 delims=, %%c in ('typeperf "\Process(%process%)\% Processor Time" -si 1 -sc 1 ^| find /V ') do (
if %%~c==-1 (
goto :end
) else (
echo %%~c%%
goto begin
)
)

:end
echo Process seems to have terminated.

Example Output:

Here’s a VBscript that is little different but still reports CPU time for every process. Good starting point if you need to hack something up.

I previously posted up a pretty lengthy entry on using WMIC to find CPU usage in the event you might be intested in that method as well.

strComputer =.
Set objWMIService = GetObject(winmgmts: & strComputer & rootcimv2)
Set colProcess = objWMIService.ExecQuery(Select * from Win32_PerfFormattedData_PerfProc_Process,,48)
For Each obj in colProcess
If obj.Name <> Idle  And obj.Name <> _Total Then
        WScript.echo obj.Name & , & obj.PercentProcessorTime
End If
Next

Visualizing SQLIO: Disk benchmark results using a PivotChart

This is a quick video of what I was working on for a little today. I created a batch script that will benchmark a disk(s) using SQLIO and record the output to a single file (or multiple, if necessary). After benchmarking completes, I run SQLIOResults and choose the output file that was created by my batch script.

Once SQLIOResults parses the SQLIO output and finishes inserting it into Excel, I create a PivotChart to compare the disk(s) IOPS and MB/s at each of the different test levels.

Hopefully someone else will find this useful. Also, if anyone knows how I can create a pivot chart in Powershell (if there’s a COM call), please let me know so I can completely automate this!

[SLVideoPlayer file=Visualizing_SQLIO.wmv, width=640,height=480 /]