Create temp directory

Create a teporary directory using a batch file
AnukAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

webbster20Commented:
mkdir c:\temp2
set temp=c:\temp2
0
greg wardSystems EngineerCommented:
or if the user is not admin
cd %userprofile%
mkdir temp2
temp2 will now be created here c:docs and setts/usersname/temp2
 
Greg

0
AnukAuthor Commented:
What if  C:\temp2  already exists?
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

webbster20Commented:
don't run mkdir, mkdir was just for illustrative purposes, really.

just don't include mkdir C:\temp2.
0
AnukAuthor Commented:
What if c:\temp2 exists but I don't know it exists?
0
AnukAuthor Commented:
What I need to do is create a new temporary directory that has no files in it. I can't use a directory that already exists.
0
webbster20Commented:
Ahh. Can we know the purpose of this? Is it going to be a Windows Temp directory? You could use a file name that is not common, say, Temp12345, but there is always a slim chance that a folder can already be in a directory.

I did temp2 because my work PC didn't have it and I wanted to watch it create it and change it to the temp dir.
0
AnukAuthor Commented:
Iit is used on an installation of a program from an install program that is downloaded from a web site. It is installed on some unknown computer somewhere out there on the internet.

Does creating a directory that exists cause an error ... I can try it.
0
webbster20Commented:
No, the directory will not be created because it already exists.
0
webbster20Commented:
It will error you with:

C:\>mkdir c:\temp2

A subdirectory or file c:\temp2 already exists.
0
AnukAuthor Commented:
I should be able to deal with that in the Batch file until I get a file name that works. Thanks
0
Steve KnightIT ConsultancyCommented:
Try this for a dir based on the current time under the existing temp dir.

@echo off
REM Take the time and remove the : from it
set mytemp=%time::=%
REM Remove any spaces in the time leaving %temp%\anuk=hhmmss.hh
set mytemp=%temp%\anuk-%mytemp: =%
REM If it should exist then try again with a 1 on the end
if exist %mytemp%\nul set mytemp=%mytemp%1
mkdir %mytemp% 2>NUL
echo %mytemp%%
0
greg wardSystems EngineerCommented:
If you create based on time its going to be tricky later.
but so are all solutions where you dont know where your temp directory is.
you could do something inside C:\WINDOWS\Temp
why dont you want it to overwite a folder?
Greg
0
Steve KnightIT ConsultancyCommented:
Creating based on time (and I suggested already being inside temp in my script above) is fine if you are using it all in the same script, that is why I assigned it to a variable.  You can use that variable throught the script, i.e.

@echo off
REM Take the time and remove the : from it
set mytemp=%time::=%
REM Remove any spaces in the time leaving %temp%\anuk=hhmmss.hh
set mytemp=%temp%\anuk-%mytemp: =%
REM If it should exist then try again with a 1 on the end
if exist %mytemp%\nul set mytemp=%mytemp%1
mkdir %mytemp% 2>NUL
echo Using temp dir %mytemp%
copy xyx.something %mytemp%
echo Maybe unzip and install it in that dir?
REM Remove directory again
rd %mytemp% /s /q

0
t0t0Commented:
Simply put:

(1) Create a static temporary folder named TEMP123.

   SET MyTemp=%temp%\TEMP123
   MKDIR %MyTemp%


(2) Create a static temporary folder based on the name of your batch file itself.

   SET MyTemp=%temp%\%~n0
   MKDIR %MyTemp%


NOTE1: So, if your batch file is named 'ProcFiles.Bat' then your new temporary folder will be named:

   ProcFiles


NOTE 2: All temporsry folders are rooted off %temp%. Enter the following command:

   SET %temp%

to find where your Windows-assigned temporary is. It should be something like this:

   C:\Documents and Settings\Paul\Local Settings\Temp

Your new user-assigned temporary folder is %MyTemp%. So, entering the following command:

   SET %MyTemp%

will now display something like this:

   C:\Documents and Settings\Paul\Local Settings\Temp\ProcFiles

The full path of your temporary folder will vary depending on the name (in this case 'Paul') of the logged on user.

 
(3) Create a RANDOM name consisting of digits 0~9 (say, 12 digits long).

   setlocal enabledelayedexpansion
   set MyTemp=

   for /l %%a in (1,1,12) do (
      set /a digit=!random! %% 9
      set MyTemp=!MyTemp!!digit!
   )

   set MyTemp=%temp%\%MyTemp%
   mkdir %MyTemp%


(4) Create a RANDOM alphanumeric (mixed case) temporary foldername (20 characters long):

   setlocal enabledelayedexpansion
   set MyTemp=

   set MinimumLength=20
   set MaximumLength=20

   set Integers=0123456789
   set LowerCase=abcdefghijklmnopqrstuvwxyz
   set UpperCase=ABCDEFGHIJKLMNOPQRSTUVWXYZ

   set RandomCharacters=%Integers%%Uppercase%%Lowercase%
   set /a TotalLength=(%random% %% (%MaximumLength% - %MinimumLength% +1)) + %MinimumLength%
   
   for /l %%a in (1,1,%TotalLength%) do (
      set /a ptr=!random! %% 61
      for %%b in (!ptr!) do (
         set MyTemp=!MyTemp!!RandomCharacters:~%%b,1!
      )
   )

   set MyTemp=%temp%\%MyTemp%
   mkdir %MyTemp%


FINALLY - What if the foldername already exists?

The easiest way to determine whether a folder already exists is to attempt to create it and examine the system ERRORLEVEL value immediately afterwards. If it is '0' then the new folder was successfully created - otherwise, you would need to loop back to the start of the code (which generates your foldername) and get another foldername.

Also, when attempting to create a folder in this fashiion, it is customery to redirect any error messege to nul, because we expect an error might occur and we don't want it displayed on the screen. Therefore, you would use the following command to create a temporary folder.

   MKDIR %MyTemp% 2>NUL
   IF ERRORLEVEL 1 GOTO Loop


Putting all this together, suppose you want to generate a 15-character wide temporary foldername of mixed case and digits 0~9. You would use the following code:


   setlocal enabledelayedexpansion

   set MinimumLength=20
   set MaximumLength=20

   set Integers=0123456789
   set LowerCase=abcdefghijklmnopqrstuvwxyz
   set UpperCase=ABCDEFGHIJKLMNOPQRSTUVWXYZ

   set RandomCharacters=%Integers%%Uppercase%%Lowercase%
   set /a TotalLength=(%random% %% (%MaximumLength% - %MinimumLength% +1)) + %MinimumLength%
   
   :: -----------------------------------------------------------------------
   :: Generate and create temporary folder
   :: -----------------------------------------------------------------------
   :loop
      set MyTemp=
     
      for /l %%a in (1,1,%TotalLength%) do (
         set /a ptr=!random! %% 61
         for %%b in (!ptr!) do (
            set MyTemp=!MyTemp!!RandomCharacters:~%%b,1!
         )
      )

      set MyTemp=%temp%\%MyTemp%
      mkdir %MyTemp%
   if errorlevel 1 goto Loop
   :: -----------------------------------------------------------------------

   ::
   :: The rest of your code.
   :: At this point, the new temporary folder has been created.
   :: You can reference it with the variable %MyTemp% or !MyTemp!
   ::



0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
t0t0Commented:
Oops!! I meant (15 characters long would be):


Putting all this together, suppose you want to generate a 15-character wide temporary foldername of mixed case and digits 0~9. You would use the following code:


   setlocal enabledelayedexpansion

   set MinimumLength=15
   set MaximumLength=15

   set Integers=0123456789
   set LowerCase=abcdefghijklmnopqrstuvwxyz
   set UpperCase=ABCDEFGHIJKLMNOPQRSTUVWXYZ

   set RandomCharacters=%Integers%%Uppercase%%Lowercase%
   set /a TotalLength=(%random% %% (%MaximumLength% - %MinimumLength% +1)) + %MinimumLength%
   
   :: -----------------------------------------------------------------------
   :: Generate and create temporary folder
   :: -----------------------------------------------------------------------
   :loop
      set MyTemp=
     
      for /l %%a in (1,1,%TotalLength%) do (
         set /a ptr=!random! %% 61
         for %%b in (!ptr!) do (
            set MyTemp=!MyTemp!!RandomCharacters:~%%b,1!
         )
      )

      set MyTemp=%temp%\%MyTemp%
      mkdir %MyTemp%
   if errorlevel 1 goto Loop
   :: -----------------------------------------------------------------------

   ::
   :: The rest of your code.
   :: At this point, the new temporary folder has been created.
   :: You can reference it with the variable %MyTemp% or !MyTemp!
0
t0t0Commented:
Actually, when attempting to create folders, as a precaution, where there might be spaces in the folder names, it is good practice to use double-quotes like this:

   MKDIR "%MyTemp%"
0
t0t0Commented:
Oh, (I'm making a pigs ear of this)...

In the code above, please change the line (near the end):

      mkdir %MyTemp%

to:

      mkdir "%MyTemp%" 2>nul

0
BillDLCommented:
Hi Anuk

You explained earlier:
"It is used on an installation of a program from an install program that is downloaded from a web site.  It is installed on some unknown computer somewhere out there on the internet."

Does this mean that YOU are creating a setup package that others can install from the Web?

If so, I think it's best if you use some standard methods to create your setup package, or you run the risk of:
1. Messing up the computer on which the program installs
2. Causing a failed installation when AntiVirus or Windows doesn't like the methods
3. Leaving behind all kinds of "temp" files on the computer it installed to.

Standard installer packages are designed to validate requirements, comply with accepted and safe setup routines, only install what they need to install dependent on the validation checks, create a method of uninstalling, and clean up again after they run.

If that is NOT what you meant, then just ignore this.

There is one method that you may not yet have considered, and that is the creation of a "Globally Unique Identifier" or GUID number to use for a folder name.  This can be achieved using a simple Visual Basic Script:

'CreateGuid.vbs
Dim objTL : Set objTL = CreateObject("Scriptlet.TypeLib")
Wscript.Echo objTL.Guid

When run using WScript.exe it will show a little message dialog with the GUID, and run using CScript.exe it displays the GUID in a "DOS" window.

If you are curious to know how "Unique" the generated number is, and what the chances of a randomly generated one being the same as another, then read these pages:

http://en.wikipedia.org/wiki/Globally_Unique_Identifier
http://en.wikipedia.org/wiki/UUID
http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx

A batch file can be used to create and run a temporary *.vbs file, capture the GUID as a variable for re-use, and then delete the *.vbs file.  The following batch file demonstrates the theory.

Bill
@echo off
SetLocal EnableDelayedExpansion

set CurrDir=%~dp0
set CurrDir=%CurrDir:~0,-1%

REM Write a VBS file on the fly
echo Dim objTL : Set objTL = CreateObject("Scriptlet.TypeLib")>"%CurrDir%\CreateGUID.vbs"
echo Wscript.Echo objTL.Guid>>"%CurrDir%\CreateGUID.vbs"

REM GUID format is {F931AF3A-1EF4-45FB-A616-A04BF02634D7}

REM Run the Script and store results in variable
for /f %%a in ('call CScript //NoLogo "%CurrDir%\CreateGUID.vbs"') do (
    set GUID=%%a
    set GUID=!GUID:~1,-1!
)

REM Optional part for verifying only.
REM Create a log of numbers to demonstrate uniqueness
echo !GUID!>>"%CurrDir%\GUID_Log.txt"

echo The GUID generated is: !GUID!
echo.
echo This can be used as the name of a new folder.
echo.

pause
REM Remove temporary VBS file
del "%CurrDir%\CreateGUID.vbs" > nul

Open in new window

0
Steve KnightIT ConsultancyCommented:
I guess we'll never know any more about what was needed specifically.
Steve
0
AnukAuthor Commented:
I am using Winzip self extractor to install the files. It runs a batch file that starts an excel file. I have a VBA program in excel that sets the references and copies the files to the default directory (or a directory the user selects). However when I run the install it cannot find the files to copy them. The winzip program deletes them before they can be copied.

Winzip creates a temp folder where it puts all the files to be installed. Then it runs my batch program which loads my excel program which then sets the references and cpies the files to a directory that the user designates. Winzip then is supposed to delete the files and its temorary directory.

But my excel program can't find the files to copy.

So if I create my own temp directory, copy the files to it, then run my excel program, and after my files are copied from my temp directory ... then I can delete them.

Winzip has a way to delay the erasing of he files in its temp directory ... but I haven't been able to make the delay work.
0
BillDLCommented:
Hi Anuk

That all seems like a roundabout way to do things.

You say:
"I have a VBA program in excel that sets the references..."

What do you mean by "sets the references"?
When referring to a "VBA program" are you referring to a Macro in the Excel workbook?

I have to question whether you actually need an "Excel Program" to copy files.

I suppose it depends what the files are and where they are from.  If your "Excel Program" is a VBA Macro in the Excel Workbook unpacked (*.xls, *.xlt, *.xlsm, or whatever), and shows a a "File > Save As" dialog to the user, then that all seems a bit unnecessary.

You could instead have separate Excel files (workbooks) unpacked by the self-extractor, to the default or named Temp folder you set when creating the self-extractor, and then run a proper setup program that allows the user to choose the file copy destination.  That's all your self-extractor is doing?  Just copying Excel files to the user's choice of folder?

There are a few different ways that you could show a dialog to a user to choose a destination directory, and I'm sure it wouldn't involve using a full-blown programming interface like Visual Studio to do.

Perhaps if you explain what you mean by "sets the references" then we can suggest what I'm sure will be a more reliable and better method.

Bill
0
BillDLCommented:
Even having two WinZip Self extracting *.exe files would be better than using batch files.  One with the files inside it that is set to prompt for an "Extract To" folder, and have that packed inside your main one that is set to run the internal one after unpacking.

Have you considered using the Windows "IExpress Wizard" to create a self-extracting package?
On a Windows XP System - %SystemRoot%\system32\iexpress.exe
Just run it, choose the options yu want, the files to pack into it, and make sure you set it to prompt the user for the destination to extract the contents, along with optional messages.

I have attached a 66KB example of an IExpress package containing 3 bare *.xls files.  It is set to prompt you for an extract path and has the expected "Browse" button.  The mssages are just generic.

Save and rename, removing the *.TXT extension from the file name, and run it.
IExpress-Test-EXE.txt
0
AnukAuthor Commented:
BillDL
The Windows Express looks good. I will try it. Thanks for the tip.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft DOS

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.