Counting the number of files in a directory, command line style


I needed to count the number of files in a directory on a Windows 2003 server.  Here’s the command that can easily be scripted:

dir/b/a-d c:\directory | find /v /c “::”

You can also specify a file share instead of a directory name:

dir/b/a-d \\server\share | find /v /c “::”

If you want to count the number of files in a directory and all subdirectories, the command is:

dir/s/b/a-d \c:\directory | find /v /c “::”

Script to gracefully power off a VM guest


You can use vmware-cmd to shut down a VMware guest.  The syntax is


vmware-cmd /vmfs/volumes/datastore1/guest1/guest1.vmx stop

Powering off a VM guest is often part of a larger script, so I need to know when the guest is really down before executing the remainder of my script.  The following code checks the guest’s state using getstate.  If the state=1, which means it’s still running, the script waits for the shutdown to complete.

# gently power off VM
vmware-cmd /vmfs/volumes/datastore1/guest1/guest1.vmx stop

# check VM state 
# If not powered off (state=0), sleep, and recheck VM state in 15 seconds
while [ ` vmware-cmd /vmfs/volumes/datastore1/guest1/guest1.vmx getstate|grep on|wc -l` -eq 1 ]
do
echo "Waiting for VM guest to shutdown...."
sleep 15
let COUNT=COUNT+1

# check VM guest state 8 times
if [ $COUNT -eq 8 ]
then
echo "VM guest shutdown is taking too long. Cannot shut down guest VM."
skip="1"
fi

done

Replace datastore1 with the name of and path to your datastore.  Replace guest1 with the name of your VMware guest.  Tested on Vmware ESX 3.0.2.

Script to remotely list Windows local administrator group membership


The following script can be run against remote Windows machines, and will enumerate the contents of the remote server’s local administrators group.

It requires Sysinternals PSExec utility, and must be run with administrative credentials.  Set the four paths to the correct locations for your workstation.

REM set path to PSexec on machine the script is being run from
Set PSExecDir=c:\pstools

REM Set file that contains the list of all your remote machines
Set InputFile=C:\servers.txt

REM Set path to file where administrator group membership is logged
Set OutputFile=C:\localadmins.txt

REM set path to error log file
Set ErrorFile=C:\errors.txt

for /f %%a in (%InputFile%) do (

echo *** Checking Server %%a *** >> %OutputFile%

%PSExecDir%\psexec \\%%a net localgroup administrators >> %OutputFile%

IF ERRORLEVEL 1 (echo Problem with obtaining local administrators on %%a >> %ErrorFile%)
)

Script to find and email files in a directory


I needed to write a batch file that would email some files, and could be run as a scheduled task.  I chose to use Blat as my email program, you can download it for free from SourceForge.

The batch file requirements were: 

1.  Had to email all the .xls files in one directory from the current date.  Luckily for me the date was in the file name, so I just had to find all files in the format *MMDDYY*.xls
 
2.  The emails had to be sent “To” some users, then “CC”d to others
 
3.  I could only use free software (no shareware) but could use our internal smtp replay server to send the mail through.
 
4. The Scheduled task that executes the script must run on a Windows 2003 server.
 
The following script is what I came up with.  I’ll go through it line by line, then post the entire thing at the end.
 
****************************************************
 
Here I’m getting the current date in the month month day day year year format, and saving it to a variable named search.  This can obviously be changed to meet your particular need
REM set search date variable in MMDDYY format for file search
REM set search to month-date-year for date formatting
for /f “Tokens=1-4 Delims=/ ” %%i in (‘date /t’) do set search=%%j%%k%%l
 
Adding a blank line to the log file ReportLog.txt since I like my logs nice and neat. Makes them easy to read.
echo. >> ReportLog.txt
 
Writing the date and time the script starts to the log file ReportLog.txt
echo %date% %time% Starting script >> ReportLog.txt
 
Using the variable search, which contains the current date, I’m getting a list of all .xls files from today and saving it in FileNames.txt
dir /b “\\server\share\%search%*.xls” > FileNames.txt
 
If there’s a problem retrieving the names of the files, write a message to the log file
IF ERRORLEVEL 1 (echo %date% %time%  problem with retrieving file names >> ReportLog.txt)
 
Using find /c to count how many files are in filenames.txt, and saving that number in the variable NUMFILES
for /f “tokens=3” %%i in (‘find /v /c “SomeStringNotToBeFound” filenames.txt’) do set NUMFILES=%%i
 
If the variable NumFiles equals zero, there were no files found for today.  Skip to ZEROFILES to send an email alert
If %NUMFILES% EQU 0 GOTO ZEROFILES
 
If NUMFILES isn’t zero, then files exist that need to be emailed.  There may be more than one file, so we’re going to use a loop to process all the files listed in FileNames.txt
For /F “tokens=1-2* delims=” %%B IN (FileNames.txt) DO (
 
write the name of the file to the log file
echo file to email is %%B >> ReportLog.txt
 
Use blat.exe to send the email to addresses specified in tolist.txt
Use blat.exe to send emails as CC to addresses specified in cclist.txt
Attached file is listed at the end of the command
This command is all one line, it may wrap on the page
blat.exe -tf tolist.txt -cf cclist.txt -subject “Report %%B” -body “Here is the current report.” -server smtp.yourdomain.com -f sender@yourdomain.com -attach “\\server\share\%%B”
)
 
We’re done emailing the files, so skip over to WRITELOG
goto WRITELOG
 
Zero files were found, so we need to send an email alert
:ZEROFILES
 
write the name of the file to the log file, along with the date and time
echo %date% %time%  problem with retrieving number of current files >> ReportLog.txt
 
Use blat.exe to send an email alert to addresses specified in problist.txt
This command is all one line, it may wrap on the page
blat.exe -tf problist.txt -subject “Problem with Report” -body “Problem sending the current report.” -server smtp.yourdomain.com -f sender@yourdomain.com
 
Writing the date and time the script starts to the log file ReportLog.txt
:WRITELOG
echo %date% %time% Ending Script >> ReportLog.txt
 
****************************************************
 
The script in it’s entirely:
 
REM set search date variable in MMDDYY format for file search
REM set search to month-date-year for date formatting
for /f “Tokens=1-4 Delims=/ ” %%i in (‘date /t’) do set search=%%j%%k%%l
 
 
REM format ReportLog.txt
echo. >> ReportLog.txt
echo %date% %time% Starting script >> ReportLog.txt
 
 
REM Get the names of all log files for specified date, save to FileNames.txt
dir /b “\\server\share\%search%*.xls” > FileNames.txt
IF ERRORLEVEL 1 (echo %date% %time%  problem with retrieving file names >> ReportLog.txt)
 
REM Count how many files are in filenames.txt, put into %NUMFILES%
for /f “tokens=3” %%i in (‘find /v /c “SomeStringNotToBeFound” filenames.txt’) do set NUMFILES=%%i
 
If %NUMFILES% EQU 0 GOTO ZEROFILES
 
REM loop when more than one file to be emailed
For /F “tokens=1-2* delims=” %%B IN (FileNames.txt) DO (
echo file to email is %%B >> ReportLog.txt
blat.exe -tf tolist.txt -cf cclist.txt -subject “Report %%B” -body “Here is the current report.” -server smtp.yourdomain.com -f sender@yourdomain.com -attach “\\server\share\%%B”
)
goto WRITELOG
 
:ZEROFILES
echo %date% %time%  problem with retrieving number of current files >> ReportLog.txt
blat.exe -tf problist.txt -subject “Problem with Hold Report” -body “Problem emailing the current hold report.” -server smtp.yourdomain.com -f sender@yourdomain.com
 
:WRITELOG
REM format ReportLog.txt
echo %date% %time% Ending Script >> ReportLog.txt
 
****************************************************

Howto: Disable a NIC when running Sysprep


Disabling a network card when running sysprepping a Windows machine is easy.  Two things need to happen: 

1.  Add the following command to the [GuiRunOnce] section of your sysprep.inf file
 
Command0=”C:\temp\disablenic.cmd”
 
2.  On the machine you are sysprepping, create a C:\temp\disablenic.cmd file that contains the following:
 
netsh interface set interface “Local Area Connection 2” DISABLED
 
Change the name of the interface you want disabled as needed.  To determine the names of all network interfaces on a system, run the following command:
 
netsh interface show interface
 
Proceed with syspreping as normal. When the machine boots up, the specified network interface(s) will be disabled.

Howto automatically change the CD-ROM drive letter after running sysprep


I’m finalizing a Windows 2003 R2 build that will become our gold image, which will be the source of all new server deployments within our organization.  One challenge I had to overcome was getting the CD-ROM/DVD drive to be set to drive Z: after the syspreped image is cloned and booted.

Many people are familiar with changing drive letters within the Device Management tool aka devmgmt.msc.  I needed to automate this task so the CD-ROM drive, which shows up as drive D on my image after running sysprep, would be automatically set to drive Z.

To accomplish this, I needed three things:

  1. An entry in the [GuiRunOnce] section of my sysprep.inf file that calls a batch file after booting up the sysprep’ed image for the first time. 
  2. The batch file mentioned in step 1, changeletter.cmd runs diskpart.exe, with the parameters supplied in drives.txt
  3. The drives.txt file, which details the diskpart.exe commands that change the CD-ROM’s drive letter from drive D to drive Z.

The applicable portion on my sysprep.inf file:

[GuiRunOnce]
Command0=”C:\changeletter.cmd”

My changeletter.cmd file:

diskpart /s c:\drives.txt

My drives.txt file:

select disk 0
select volume d
assign letter z noerr

Put all these pieces together, and your CD/DVD drive should be changed to drive letter Z after booting up the sysprep’ed image.  Note that in the [GuiRunOnce] section of the sysprep.inf file, the part to the left of the equals sign is Command0, as is Command zero.  If you wanted to run additional scripts, the next would be Command1, followed by Command2, etc.

If you’re curious about diskpart.exe, check out the details on syntax in KB300415.

Find Windows system uptime from the command line


Here’s a quick and easy way of checking how long a Windows server or workstation has been up, via the command line.  It pipes the results of Net Statistics Workstation into find.  Run the following from a command prompt:

net statistics workstation | find /i “statistics since”

The results will look like

Statistics since 8/12/2009 11:08 PM

Which shows the machine has been up since 11:08pm on August 12, 2009.