Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info
titleWindows

This sample is a Windows batch file that uses a combination of environment variables set by the UEM Server and the current system date/time in an attempt to construct a unique file name used to store the output of the dir command. Because multiple instances of this script can be executing at the same time, and a process ID is not available to a Windows batch file, a loop exists to retry the file name construction if a matching file is found.


Expandpanel
@echo off

:: Main script flow
set rc=0

call :SetVariables
call :SetupOutputFile

:: Now, execute the command. Redirect the contents of this directory
:: and all subdirectories to the file identified by %fname%.

dir /o/-p/s >%fname%
set rc=%ERRORLEVEL%

:: Exit the script
goto Exit

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Subroutines 
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:SetVariables
:: Set a date string in the format yyyy.mm.dd.
for /f "tokens=2,3,4 delims=/ " %%a in ('date /t') do set dt=%%c.%%a.%%b

:: Set a time string in the format hh.mm.ss
for /f "tokens=1,2 delims=: " %%a in ('time /t') do set tm=%%a.%%b

:: Remove file extension
for /f "tokens=1,2 delims=." %%a in ("%UEMORIGFILE%") do set uemFName=%%a

:: Set the file name
set fname=%uemFName%.%dt%.%tm%.txt

:SetVariablesExit
goto :EOF

::
:: Test for the existence of the output file. If the file is found, loop 
:: for a while then reset the time variable and check again.
::
:SetupOutputFile
:: If the file doesn't exist, create it to prevent another instance of this
:: script from grabbing it.
if not exist %fname% (
echo. >%fname%
goto SetupOutputFileExit
)

:: Otherwise, wait for a count of 10,000 (approx 1 sec) and try again.
if exist %fname% for /l %%I in (1,1,10000) do echo. >NUL

call :SetVariables
goto SetupOutputFile

:SetupOutputFileExit
goto :EOF

:Exit
exit %rc%

...