I am trying to make a batch file that will make a folder on the desktop from user input. Here is my code:
echo What do you want the folder to be called?
SET /p folderName=
md C:\Users\%username%\desktop\%folderName%
However, whenever I try this, It gives me an error saying:
A subdirectory or file C:\Users\Razi\desktop\ already exists.
It doesn't seem to be noticing the %folderName% at the end.
Can somebody tell me what's wrong with my code and give an alternative? Thank you!
Oviously, %folderName% appears to be empty, as you can see in the error message which includes the path argument the md command receives. So md tries to create the already existing directory Desktop.
If the error appears even when you enter a valid directory name, I am pretty sure that the code fragment is part of a block in between parentheses, in which case you need to enable and apply delayed expansion. Otherwise you read the folderName value present before the entire block is executed.
For instance, the following block is seen as a single command line by the command interpreter; %folderName% is expanded (replaced by its value) as soon as the whole line/block is parsed:
(
echo What do you want the folder to be called?
set /P folderName=
md "%USERPROFILE%\desktop\%folderName%"
)
In the following, delayed expansion is enabled (by setlocal); to actually use it, the % expansion has been changed to !; so !folderName! is expanded (read) later, as soon as it is executed:
setlocal EnableDelayedExpansion
rem ...
(
echo What do you want the folder to be called?
set /P folderName=
md "%USERPROFILE%\desktop\!folderName!"
)
rem ...
endlocal
Note that the changed value of folderName is no longer available as soon as endlocal has been executed, or the batch file terminates (where an implicit endlocal happens).
In addition to the above, I put quotation marks around the path at the md command to avoid trouble with white-spaces or special characters, and I changed C:\Users\%USERNAME% to %USERPROFILE% as recommended in Stephan's comment.
Related
This question is related to Test IF file exist, ELSE xcopy these two files.
Background: On occasion I choose to run aGallery-dl.bat in a given folder (just one in each of 100's of folders). It first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of a red X being replaced by a yellow ! when viewing the folder with parent folder selected in File Explorer. Secondly, it calls gallery-dl.exe. I use going from red X to yellow ! to let me know I've run aGallery-dl.bat at least once. If aGallery-dl.bat completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible. All is well.
rem #echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg
Problem: Restating, Gallery-dl.bat is in each of 100's of folders. On occasion, I run one of these from within it's local folder. Line 5, if the call to the web site is successful, gallery-dl.exe creates zzzGDB.sqlite3 within the local folder.
In the previous code, when aGallery-dl.bat completed, it would just delete the Folder.jpg. This assumes the call to the web page was successful. On rare occasion, the call to the web page will fail for any number of reasons, though at close (due to that final del .\Folder.jpg), it will still delete folder.jpg.
If zzzGDB.sqlite3 was not created/not present, I need the Folder.jpg (yellow !) to remain.
So, in the below code (line 6, now blank), I've lopped off the final del .\Folder.jpg and am trying to plug-in the provided code beginning at line 7, inserting a test for zzzGDB.sqlite. If found, del .\Folder.jpg. If not found, no action is taken against folder.jpg (it remains).
(The rem statement at the very bottom is just acting as a placeholder for my own knowledge.)
rem #echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\zzzGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
if exist "%%I\zzzGDB.sqlite3" (
del "%%I\Folder.jpg"
)
rem
)
endlocal
Note: Currently, the modified code goes back through every single folder within U:\11Web\gallery-dl\deviantart\*. This action should be reserved only to the local folder. I'm guessing the below is the issue.
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*")
I don't know how to remove it and still implement everything after do?
do (
if exist ".\zzzGDB.sqlite3" (
del ".\Folder.jpg"
)
rem
)
I suggest to use following lines for aGallery-dl.bat.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || exit /B
move /Y "Folder2.jpg" "Folder.jpg"
for %%I in (.) do set "FOLDER=%%~nxI"
"%ProgramFiles(x86)%\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive "%~dp0zzzGDB.sqlite3" "https://www.deviantart.com/%FOLDER%/gallery/all"
if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
popd
endlocal
The first two lines define the execution environment for the batch file.
The third line with command PUSHD pushes the current directory path on stack and sets the directory of the executed batch file as current directory. This works even on batch file being stored on a network resource accessed using a UNC path, except there is a network problem on execution of that command line.
The command exit /B is executed in case of an error to immediately exit processing of the batch file on batch file directory could not be set as current directory. The Windows command processor runs implicitly the command ENDLOCAL in this case.
See Single line with multiple commands using Windows batch file for an explanation of operator || which results in conditionally executing exit /B only if pushd exited with a non-zero exit code indicating an error.
The fourth command line with MOVE does not really move the data of file Folder2.jpg to file with name Folder.jpg. In real it just updates the file system in this case as done also by the two commands del .\Folder.jpg and ren .\Folder2.jpg Folder.jpg in your batch file. This is just a very little bit faster method to replace one file by another file with the advantage that Folder.jpg must not exist at all for success without displaying an error message as done by command DEL on file Folder.jpg not existing.
The FOR command line determines the name of the current folder without path and assigns it to environment variable FOLDER. This is a much faster and safer solution then using the command line:
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
The command line above results in starting in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So there is executed in background with Windows installed to C:\Windows:
C:\Windows\System32\cmd.exe /c cd
The started cmd.exe executes internal command cd which outputs the full qualified folder name of current directory to handle STDOUT of background command process. This output is captured by cmd.exe processing the batch file and is processed by for after started cmd.exe closed itself after finishing execution of command CD.
The command FOR would split up the folder path into substrings (tokens) using normal space and horizontal tab as string delimiters, would look next if the first space/tab delimited string starts with a semicolon in which case the captured line would be ignored for further processing, and would assign otherwise just the first space/tab delimited string to loop variable i. So if the full qualified folder name of current directory would contain a space, this command line would fail to determine the folder name of current directory without path.
There is the dynamic variable CD of which value can be referenced with %CD%. The value is the full qualified folder name of current directory not ending with a backslash, except the root directory of a drive is the current directory. That would be identical to %~dp0 for batch file aGallery-dl.bat with the difference that %~dp0 expands to full qualified name of batch file folder always with a backslash at end.
However, neither dynamic variable CD nor %~dp0 nor execution of command CD in a separate command process in background are really useful to get name of current directory (= batch file directory) without path. The best method is using:
for %%I in (.) do set "FOLDER=%%~nxI"
This simple FOR does nothing else than getting name of current folder without path with a very fast executed file system query and assigning it to environment variable FOLDER.
Note: for %%I in ("%~dp0.") do set "FOLDER=%%~nxI" could be also used to get folder name without path of folder containing currently executed batch file if the current directory would not be the batch file directory.
The sixth command line executes gallery-dl.exe with various parameters (arguments).
Please note that "https://www.deviantart.com/"%FOLDER%"/gallery/all" is in real an invalid argument string. It is not valid to have " inside a URL. The character " is never valid inside an argument string which references a file or folder. This syntax error is detected and automatically fixed which is the reason why the command line in your batch file works at all. The correct argument string is "https://www.deviantart.com/%FOLDER%/gallery/all" with one " at beginning and one " at end and no double quote inside the argument string enclosed in double quotes.
There is standard for console applications to exit with value 0 on success and a greater value like 1 on an error. I don't know if this is true also for gallery-dl.exe, but I assume that with the command line:
if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
if not errorlevel 1 checks if exit code of gallery-dl.exe assigned to dynamic variable errorlevel is NOT greater or equal 1 which means less than 1 which means equal 0 (on executable never exiting with a negative value which is not recommended to do by a program on any operating system) which means no error occurred during execution of gallery-dl.exe. Please read the documentation of gallery-dl.exe regarding to exit codes of this program or find it out with several executions in a command prompt window and using echo Exit code is: %errorlevel% after each execution of gallery-dl.exe with success or an error (like a wrong URL).
That condition should be already enough. But there is used one more condition to check for existence of the file zzzGDB.sqlite3 in current directory only before deleting the file Folder.jpg in the current directory which is the batch file directory.
Please read issue 2 in this answer for the reason writing in batch file
if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
instead of
if not errorlevel 1 (
if exist "zzzGDB.sqlite3" (
del "Folder.jpg"
)
)
The code above works also, but requires more CPU cycles for being processed by Windows command processor than the single line with two IF commands and one DEL command on one command line.
The last but one line pops the full qualified folder name of initial current directory from stack and sets it again as current directory and the last line restores initial execution environment on starting the batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?... explains %~dp0 ... drive and path of argument 0 ... full batch file path.
del /?
echo /?
endlocal /?
exit /?
for /?
move /?
popd /?
pushd /?
set /?
setlocal /?
I am writing a batch script for the 6th assignment in my class and I have hit a snag when I am pretty much finished. (We usually focus on bash scripting, so I am new to batch)
The script functions as desired the first time running it; but behaves differently when running it for the second time.
Essentially, the script checks the value of an argument if it exists and runs specific code depending on the value. For example, if the argument is "1", then it checks the PATH variable for a directory and creates it if it doesn't exist, and if it does exist - nothing happens and it just continues the script.
The issue occurs when running the script for a second time after the PATH is modified. I receive the output "\Common was not expected at this time".
I had a similar issue when running the script the first time, but managed to fix it by including Quotation marks on both side of the evaluation on the IF statement, but now I am unsure of where to continue with this.
My code is as follows:
#echo on
IF "%1%" == "0" (
SET "VAR1=%path%"
echo.%VAR1%|findstr /C:"App0" >nul 2>&1
if errorlevel 1 SET "PATH=%PATH%%cd%\App0;"
if not errorlevel 1 echo Found
goto errorBypass
) ELSE IF "%1%" == "1" (
SET "VAR2=%path%"
ECHO %VAR2%
echo.%VAR2%|findstr /C:"App1" >nul 2>&1
if errorlevel 1 SET "PATH=%PATH%%cd%\App1;"
if not errorlevel 1 echo Found
goto errorBypass
) ELSE IF "%1%" == "" (
IF "%HUMBER_HOME%" == "" (
goto Error2
) ELSE (
CALL "HUMBER_HOME\bin\setEnv.bat"
goto errorBypass
)
)
echo HERE
:Error2
echo Error2
:errorBypass
call "run.bat"
Also, so I know for future reference - is there an effective way to debug by going line by line? or a command that can output the particular line where the error occurred? I find it somewhat difficult when one error can be caused by multiple issues in different places.
Referencing a batch file argument
Open a command prompt window and run call /?. The output help explains how to reference batch file arguments. %1 references the first argument as passed to the batch file. That can be for example 1 (not quoted argument string), but also "1" (quoted argument string). %~1 references first argument string with surrounding double quotes removed.
It is wrong to add one more % after the argument reference. The syntax %variable% is used to reference the string value of an environment variable. Batch file arguments are referenced only with percent sign and digit without or with a modifier between. There is no more percent sign after the digit. That is also the reason why 1, 2, 3, ... are not possible as names for environment variables.
So not good is IF "%1%" == "0" ( because of this can result on batch file called with "1" as first argument in execution of the command line:
IF ""1"" == "0" (
The much better syntax is IF "%~1" == "0" ( which results in execution of the command line:
IF "1" == "0" (
See my answer on difference between “…” and x“…” in batch for more details on how to evaluate batch file arguments.
Appending a folder path to local PATH
The environment variable PATH holds a comma-separated list of folder paths whereby the list separator is a semicolon instead of a comma.
Therefore a ; at end of PATH means there is one more folder path which is an empty folder path. It is possible to specify an empty folder path in the middle or at end of PATH, but it is bad practice to do so because of PATH should not contain empty folder paths.
For that reason the following command line in your code is not good:
if errorlevel 1 SET "PATH=%PATH%%cd%\App0;"
There is also missing ; in case of PATH does not already end with a semicolon which could be a reason for the error message on second execution of the batch file.
The better code can be seen below on completely revised batch file code.
Referencing current directory
It is possible to reference the current directory with %CD% which can differ from batch file directory referenced with %~dp0. %~dp0 references drive and path of argument 0 which is the batch file itself. The batch file path string referenced with %~dp0 always ends with a backslash. Therefore no additional backslash should be used after %~dp0 on concatenating it with a file/folder name.
The dynamic environment variable CD ends usually with no backslash at end. So in most cases %CD% must be concatenated with an additional \ with a file/folder name. But there is one exception which must be taken into account on using %CD% in a batch file: %CD% expands to a string with \ at end on current directory being the root directory of a drive, for example C:\ or D:\. So it is always necessary on using %CD% to check if the string already ends with a backslash before appending a file/folder name without or with an additional backslash.
Other recommendations
The usage of a command block starting with ( and ending with ) should be avoided on using environment variables defined/modified within a command block and referenced within the command block as this requires the usage of delayed expansion as explained by help output on running set /? in a command prompt window on an IF and a FOR example on which command blocks are used usually. The Windows command processor is designed primary for executing one command line after the other. The usage of command blocks can speed up the execution of a batch file in some cases, but in many cases it is better to avoid them.
See debugging a batch file with a short description how to debug a batch file. A single step execution is not really possible. But cmd.exe shows on which line or command block an error occurred resulting in exiting batch file execution and what is the error.
Revised batch file code
Here is the revised batch file code:
#echo off
goto Main
:AddPath
echo %PATH%;|%SystemRoot%\System32\findstr.exe /I /C:"\%~1;" >nul 2>&1
if not errorlevel 1 echo Found %~1 in PATH& goto :EOF
set "Separator=;"
if "%PATH:~-1%" == ";" set "Separator="
if "%CD:~-1%" == "\" (set "AppPath=%CD%%~1") else set "AppPath=%CD%\%~1"
set "PATH=%PATH%%Separator%%AppPath%"
set "AppPath="
set "Separator="
goto :EOF
:Main
if "%~1" == "0" call :AddPath App0 & goto errorBypass
if "%~1" == "1" call :AddPath App1 & goto errorBypass
if not "%~1" == "" goto RunApp
if "%HUMBER_HOME%" == "" goto Error2
if exist "%HUMBER_HOME%\bin\setEnv.bat" (
call "%HUMBER_HOME%\bin\setEnv.bat"
goto errorBypass
)
echo File "setEnv.bat" in subdirectory "bin" in directory
echo defined by environment variable HUMBER_HOME not found.
echo HUMBER_HOME directory: "%HUMBER_HOME%"
echo/
pause
goto :EOF
:RunApp
echo HERE
goto :EOF
:Error2
echo Error2
goto :EOF
:errorBypass
if exist "run.bat" call "run.bat"
There is defined the subroutine AddPath at top of the batch file which is a bit unusual. So the second line with goto Main results in jumping over code of the subroutine on starting the execution of the batch file.
The subroutine AddPath is called with either App0 or App1 on first argument being 0 or "0" or 1 or "1".
The first line in AddPath outputs current value of local environment variable PATH with a semicolon appended and redirects this output to FINDSTR which searches case-insensitive and literally for the first argument string passed to the subroutine after a backslash and ending with a semicolon. The additional \ and ; should avoid a false positive on any folder path in PATH containing by chance also App0 or App1 somewhere in the middle of the folder path. This small enhancement is not 100% fail safe, but should be good enough.
FINDSTR exits with 0 on searched string found in line. In this case just an information message is output and the subroutine is exited which results in batch file execution being continued on main code on which the subroutine was called before. Otherwise the passed application name must be added to local PATH.
See also:
Where does GOTO :EOF return to?
Single line with multiple commands using Windows batch file
So first the environment variable Separator is defined with ; as value. But if local PATH already ends with a backslash although it should not, the environment variable is deleted immediately. Please note that the command line comparing last character of PATH with ; can fail if PATH ends with ". So this simple version is not 100% fail safe.
Next the current directory path is concatenated with the passed application folder name without or with an additional backslash depending on current directory being root directory of a drive or a subdirectory of any directory.
Then the local PATH is extended with appending the application path according to passed argument without or with an additional semicolon before.
Finally the no longer needed environment variables Separator and AppPath are deleted before exiting the subroutine.
A main mistake in main code as posted in question are the missing percent signs around environment variable HUMBER_HOME on calling batch file setEnv.bat in subdirectory bin of the directory assigned to environment variable HUMBER_HOME. This could be another reason for the error message on second execution of the batch file.
The revised code first checks if each batch file to call really exists before calling it.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
findstr /?
goto /?
if /?
pause /?
set /?
In a batch file, I need to get a path from the user, remove the trailing backslash if they included it, and then check if any files with the .sql extension are in the folder that they specified. If not, I want to return them to the variable entry section.
Here's what I have:
REM Get the folder paths from the user
:setfolderpaths
set /p SCRIPTFOLDER="D:\Mark\Centriq Extraction Projects\"
set /p OUTPUTFOLDER="D:\Mark\Centriq Extraction Projects\"
REM View what the user entered (testing only)
echo %SCRIPTFOLDER%
echo %OUTPUTFOLDER%
REM pause here to check the user entry (testing only)
#pause
REM Remove trailing slashes from the folder path if they exist
if %SCRIPTFOLDER:~-1%==\ set SCRIPTFOLDER=%SCRIPTFOLDER:~0,-1%
if %OUTPUTFOLDER:~-1%==\ set OUTPUTFOLDER=%OUTPUTFOLDER:~0,-1%
REM If the folder the user entered doesn't exist, go back to the folder entry section
if not exist %SCRIPTFOLDER% + "\*.sql" (
goto setfolderpaths
)
However, when I run the file, after I press a key to continue at the pause, the cmd window closes immediately. I've checked that the lines removing the backslash work, so the problem seems to be in my if not exist check.
EDIT
Apparently, I had some code in my sample that was confusing what I am trying to figure out. I've added comments to explain what I'm doing in each part. I just need to figure out why my check for.sql files in the user-specified folder isn't working.
UPDATE
Okay, I cleaned up my quoting issues per #LotPings' suggestions.
So, when I put an echo right before the if check:
echo %SCRIPTFOLDER%
#pause
That's displaying a valid path that I know does have sql files in it. So this code isn't working:
if not exist "%SCRIPTFOLDER%\*.sql" (
goto setfolderpaths
)
When I hit a key to continue at the pause the cmd window closes.
This are all quoting issues.
If the double quote is the last char (as is the case above) and you remove it,
the string has only a leading d'quote and still a trailing backslash.
Better quote always like this:
:setfolderpaths
set "SCRIPTFOLDER=D:\Mark\Centriq Extraction Projects\"
set "OUTPUTFOLDER=D:\Mark\Centriq Extraction Projects\"
echo %SCRIPTFOLDER%
echo %OUTPUTFOLDER%
#pause
REM Remove trailing slashes from the folder path if they exist
if "%SCRIPTFOLDER:~-1%"=="\" set "SCRIPTFOLDER=%SCRIPTFOLDER:~0,-1%"
if "%OUTPUTFOLDER:~-1%"=="\" set "OUTPUTFOLDER=%OUTPUTFOLDER:~0,-1%"
if not exist "%SCRIPTFOLDER%\*.sql" (
goto setfolderpaths
)
Also there is no string concatenation with + you used in your if.
Read the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? and you know what is wrong on first two SET command lines.
Original question: The folder paths are assigned to the environment variables with both double quotes and so the last character of both environment variable values is " and not the backslash as expected by you.
Edited question: The two folder paths are displayed as prompt text.
The wrong position of first " on SET command lines is responsible for syntax errors on remaining lines as well as + on IF condition line. Windows command processor does not support string concatenations using an operator +. The strings to concatenate must be just written concatenated in the batch file.
Here is a batch file which prompts the user for both paths and runs some checks as the user has the freedom to enter nothing or strings which could do something really bad without appropriate checks in right sequence without using delayed environment variable expansion. The command lines are modified by Windows command processor before execution by each %ScriptFolder% and %OutputFolder% reference. It never really matters what is written in batch file. It matters how each command line or an entire command block looks like after parsing by Windows command processor cmd.exe on execution of batch script.
#echo off
:GetScriptFolderPath
set "ScriptFolder="
set /P "ScriptFolder=Enter script folder path: "
rem Has the user not entered any string?
if not defined ScriptFolder goto GetScriptFolderPath
rem Remove all double quotes from entered string.
set "ScriptFolder=%ScriptFolder:"=%"
rem Has the user entered a string consisting only of double quotes?
if not defined ScriptFolder goto GetScriptFolderPath
rem Remove a backslash at end of user entered string.
if "%ScriptFolder:~-1%" == "\" set "ScriptFolder=%ScriptFolder:~0,-1%"
rem Has the user entered just a backslash (with one or more double quotes)?
if not defined ScriptFolder goto GetScriptFolderPath
rem Is the user entered string really a path to a directory
rem which really exists and contains at least one *.sql file?
if not exist "%ScriptFolder%\*.sql" goto GetScriptFolderPath
:GetOutputFolderPath
set "OutputFolder="
set /P "OutputFolder=Enter output folder path: "
if not defined OutputFolder goto GetOutputFolderPath
set "OutputFolder=%OutputFolder:"=%"
if not defined OutputFolder goto GetOutputFolderPath
if "%OutputFolder:~-1%" == "\" set "OutputFolder=%OutputFolder:~0,-1%"
if not defined OutputFolder goto GetOutputFolderPath
rem Is the user entered string really a path to an existing directory?
if not exist "%OutputFolder%\" goto GetOutputFolderPath
Note: The batch file user can also drag & drop a folder path for example from Windows Explorer into the console window to enter the path and needs to press next only RETURN or ENTER to complete the input prompt.
It is also possible to use set "ScriptFolder=D:\Mark\Centriq Extraction Project" instead of just set "ScriptFolder=" to define a non empty default on which the user has just to press RETURN or ENTER for using it. A default folder path can be also set for the output folder.
I am trying to write a log that a user will create in a batch file, as a small little game, but I can't seem to get the correct directory of the file down. I want to write to this directory:
BatchfileandFolder\subfolder1\subfolder2\ThedataisHere.txt
This is the code I have (I really don't know what I am doing)
Echo Write a piece of text here
set /p UserData=
>>\subfolder1\subfolder2\"ThedataisHere.txt" echo %UserData%
It is essential trying to dig deeper into the directory, but I don't know the exact command, and the help menu for CD, and PATH on the cmd.exe promt don't really help me that much.
Thank you for real human contact, speaking real English
#ECHO OFF
SETLOCAL
SET "logfile=u:\sub folder1\sub folder2\ThedataisHere.txt"
FOR /f "delims=" %%a IN ("%logfile%") DO MD "%%~dpa"
Echo Write a piece of text here
set /p UserData=
>>"%logfile%" echo %UserData%
GOTO :EOF
This method uses a variable logfile so that you aren't forever typing out the name (and avoid the pain if you want to change the names or directories, and the method allows you yo use multiple logfiles easily if you want)
I've deliberately used spaces in directory names to prove the method. The directory gets created immediately after the logfile name is set
append 2>nul to the md instruction line to suppress the directory already exists message
From there, simply use >>"%logfile%" to create the log. The quotes are not required if the filename doesn't contain separators like spaces.
Note that if the first character of the directory specified is \ then the directory is relative to the root, but if it is not then the directory is relative to the current directory on the destination drive. u: is a drive specifier, not a directoryname; I use u: as my test drive. Your choice is up to you.
If the directory structure already exists, it's pretty simple:
#echo off
set /p UserData=Write some text here:
#echo %UserData% >> "subfolder1\subfolder2\TheDataIsHere.txt"
If it doesn't exist already, you have to create it first (tested on Win7 64 bit):
#echo off
if not exist "subfolder1" md "subfolder1"
if not exist "subfolder1\subfolder2" md "subfolder1\subfolder2"
set /p UserData=Write some text here:
#echo %UserData% >> "subfolder1\subfolder2\TheDataIsHere.txt"
Although your description is ample, some important points are missing. It is obvious that you know "How to change the directory that a batch file will output text to", because you use the >> \subfolder\... notation, so this is not your problem. I can only guess that you want to know "How to get the directory where a batch file is located", so you can write to a log file placed two levels below that directory. If this is your problem, then you may use the %~P0 notation, that represent the path of the batch file; that is:
>> "%~P0subfolder1\subfolder2\ThedataisHere.txt" echo %UserData%
Note that the value returned by %~P0 ends in a backslash, so %~P0 must not be separated by an additional backslash from subfolder1; also note that the quotes must enclose the whole path of the file.
If this is not what you want, please carefully describe your real problem. Anyway, try to be clearer in future questions.
I have come across some odd behaviour with a batch script recently that I haven't seen before.
Below is what I have had to do to get my script to work. Below is just a piece of the overall script but shows the issue. In short I am having to constantly switch drives in the code. This becomes an issue when using the blat.exe with the attachment on a different drive.
Set DataFile=Test%Date:~-7,2%%Date:~-10,2%.csv
:: Echos the correct name
echo %DataFile%
:: Wouldn't expect to need the two lines below
D:
cd %DATAPATH%
:: If file not present exit
IF NOT EXIST %DataFile% (
echo No File Exists
Exit
)
What I want to be able to do to simplify things (what I would usually do on other environments)
Set DataFile=Test%Date:~-7,2%%Date:~-10,2%.csv
:: Echos the correct name
echo %DataFile%
:: If file not present exit
IF NOT EXIST %DataFile% (
echo No File Exists
Exit
)
Hopefully that makes sense. It seems to be an environment issue or similar, but I cant find anything obvious.
Thank you for any help.
Edit for solution:
As mentioned in a comment below, the underlying issue sent me on a complete wild goose chase and hence the example provided most probably made little to no sense. The problem was a comment inside of the IF statement which I excluded from the examples provided to keep things clean. Turned out the comment was the problem!
The below does not work and complains about a missing ')'
IF NOT EXIST %Filepath%\%FileName% (
echo the file does not exist
:: call {path to an executable}
)
.. Continue script
The script below does work
IF NOT EXIST %Filepath%\%FileName% (
echo the file does not exist
)
:: call {path to an executable}
.. Continue script
Thanks for your help with he issue.
One thing is you are quoting both path1 and file1 when you assign them a value. This will cause a problem when dealing with full paths:
move %path1%%file% %path2%
Expands to (using your values):
move "path1""file1" "path2"
Instead do not quote paths and file name which will be concatenated later, rather quote them when they are combined:
set path1=C:\My Path\
set file1=myfile.txt
set path2="C:\New Path\"
REM Combined path is quoted.
move "%path1%%file%" %path2%
The above expands to:
move "C:\My Path\myfile.txt" "C:\New Path\"
For your full script, try this:
REM Do not quote path/files which are to be combined.
set path1=path1
set file1=file1
set path2="path2"
REM Quote path here since it isn't quoted in the declaration.
IF NOT EXIST "%path1%" (
md "%path1%"
)
REM Combined path is quoted.
move "%path1%%file%" %path2%
::exe below is on another drive
call [path_to_exe].exe