The code below should archive some files by moving them into a subfolder. The batch file asks the user for the folder path. Then a subfolder should be created and if that was successful, it should move all files in the user input directory into the subdirectory. It works, but it closes although using pause. It does not output anything about a syntax error or anything at all. Please let me know if somebody notices something.
#echo off
SETLOCAL EnableDelayedExpansion
echo Insert path:
set /p path=
echo the path is %path%
cd %path%
echo The files will be moved to a new folder
pause
mkdir %path%\archived_files
IF EXIST "archived_files" (
for /f %%A in ('DIR /A /D /B') do (
echo %%A && move /Y %path%\%%A %path%\archived_files)
echo Folder "archived_files" created or already exists
) else ( echo Folder "archived_files" does not exist )
echo the files have been transferred
pause
ENDLOCAL
I suggest to use this batch file for the file moving task.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "BatchFileName=%~nx0"
set "BatchFilePath=%~dp0"
set "UserPath=%~1"
if defined UserPath goto ChangeFolder
:UserPrompt
set "UserPath="
set /P "UserPath=Enter path: "
rem Has the user not entered a string?
if not defined UserPath goto UserPrompt
rem Remove all double quotes from input string.
set "UserPath=%UserPath:"=%"
rem Has the user entered just one or more double quotes?
if not defined UserPath goto UserPrompt
:ChangeFolder
pushd "%UserPath%" 2>nul || (echo Folder "%UserPath%" does not exist.& goto UserPrompt)
for /F "eol=| delims=" %%I in ('dir /A-D /B 2^>nul') do goto CreateSubfolder
echo The folder does not contain any file to archive.& goto EndBatch
:CreateSubfolder
md "archived_files" 2>nul
if not exist "archived_files\" echo Failed to create subfolder: "archived_files"& goto EndBatch
rem It must be avoided that the currently running batch file is moved too.
set "ExcludeFileOption="
for %%I in ("%UserPath%\") do set "CurrentFolderPath=%%~dpI"
if "%CurrentFolderPath%" == "%BatchFilePath%" set "ExcludeFileOption= /XF "%BatchFileName%""
rem The command MOVE used with wildcard * does not move hidden files. A FOR loop
rem with MOVE is slow in comparison to usage of ROBOCOPY to move really all files.
rem The ROBOCOPY option /IS can be removed to avoid moving same files existing
rem already in the subfolder archived_files from a previous batch execution.
echo The files are moved to a new folder.
%SystemRoot%\System32\robocopy.exe . archived_files%ExcludeFileOption% /MOV /R:2 /W:5 /IS /NDL /NFL /NJH /NJS
if not errorlevel 2 if errorlevel 1 echo All files are moved successfully.
:EndBatch
popd
endlocal
pause
The batch file can be started with a a folder path as argument. So it is possible to right click on the batch file and click in opened context menu in submenu Send to on item Desktop (create shortcut). The .lnk file created on the user´s desktop can be renamed now also via context menu or key F2 to whatever name is useful like Archive files. Then the shortcut file can be cut with Ctrl+X and pasted with Ctrl+V in the folder %APPDATA%\Microsoft\Windows\SendTo to have in Send to context submenu the menu item Archive files. This makes it possible to right click on a folder and click in opened context menu in submenu Send to on Archive files to run the batch file without the need to enter a folder path manually.
The batch file prompts the user for the path if not started with a folder path as first argument or the folder cannot be found at all. This user prompt is done using a safe method. The batch file makes the passed or entered folder temporarily the current folder for the remaining commands using PUSHD and POPD instead of CD to work also with UNC paths.
There is checked next if the folder contains any file at all. Otherwise the user is informed that the directory does not contain files to archive and batch file ends without any further action.
The file movement is done with ROBOCOPY for the reasons described in a remark in the batch file which requires Windows Vista or a newer Windows version or Windows Server 2003 or a newer Windows server version.
I recommend to see also:
Debugging a batch file which answers your question.
What is the reason for "X is not recognized as an internal or external command, operable program or batch file"? It explains why path as name for the environment variable to assign the user entered path is a really bad idea.
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input? It explains the reasons for using the additional code to evaluate the string entered by the user.
Why is no string output with 'echo %var%' after using 'set var = text' on command line? It explains the recommended syntax for the (re)definition of an environment variable and why using this syntax.
Syntax error in one of two almost-identical batch scripts: ")" cannot be processed syntactically here describes several common issues made by beginners in batch file coding like not enclosing a file/folder path in double quotes.
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 %~nx0, %~dp0 and %~1 whereby argument 0 is always the batch file itself.
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
pause /?
popd /?
pushd /?
rem /?
robocopy /?
set /?
setlocal /?
Other useful documentations used to write this code:
single line with multiple commands using Windows batch file
the Microsoft documentations for the used Windows Commands
the SS64 documentations for the used Windows CMD commands, especially:
ROBOCOPY.exe
ROBOCOPY Exit Codes
the Microsoft documentation about Using command redirection operators
and the SS64 documentation How-to: Redirection
Note: The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background with %ComSpec% /c and the command line within ' appended as additional arguments.
Related
I'm getting wrong with the older version Microsoft Edge and now I can't open pdf files with it. Though the newer version is available, I don't really like the newer version.Yesterday I learned that I can use Microsoft Edge to open pdf file through command line like below, but I don't know how to dynamically attach the filepath of the pdf to my batch script when I choose to open the pdf with my batch script.
start shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge file:\\\d:\\xxx.pdf
Open a command prompt, run call /? and read the output help carefully and completely. It explains how batch file arguments can be referenced from within a batch file. Argument 0 is always the batch file itself.
The batch file for your purpose could be coded as:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=%~1"
if not defined FileName goto PrintHelp
set "FileName=%FileName:"=%"
if not defined FileName goto PrintHelp
if "%FileName%" == "/?" goto PrintHelp
set "FileName=%FileName:/=\%"
if not exist "%FileName%" (
echo ERROR: File not found: "%FileName%"
echo/
pause
goto EndBatch
)
set "FileName=%FileName:\=/%"
if not "%FileName:~0,1%" == "/" set "FileName=///%FileName%"
start "" shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge "file:%FileName%"
goto EndBatch
:PrintHelp
echo INFO: %~nx0 must be called with name of a file to open in Microsoft Edge.
echo/
pause
:EndBatch
endlocal
I do not really understand why a batch file is needed at all to open PDF files in Microsoft Edge. It would be also possible to simply associate the file extension .pdf with Microsoft Edge to get PDF files opened by default with Microsoft Edge.
The following command line can be executed in a command prompt window to get displayed which application is associated currently with file extension .pdf and which command is used to open a PDF file with %1 being the placeholder for the file name:
for /F "skip=1 tokens=2*" %I in ('%SystemRoot%\System32\reg.exe query HKEY_CLASSES_ROOT\.pdf /ve 2^>nul') do %SystemRoot%\System32\reg.exe query "HKEY_CLASSES_ROOT\%J\Shell\Open\Command" /ve
For understanding the commands used in the batch file 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.
echo /?
endlocal /?
goto /?
if /?
pause /?
set /?
setlocal /?
start /?
See also the Wikipedia article about file URI scheme. It would be necessary to percent encode the file name for a 100% correct file URL, but Microsoft Edge supports also not correct encoded file URLs containing for example a space character instead of %20 or the umlaut ä instead of %c3%a4.
I'd assume that you could open your pdf located in the same directory as your batch-file, with the assistance of powershell:
#Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
Set "filename=myfile! - 100%% virus free.pdf"
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command "[System.Diagnostics.Process]::Start(\"msedge\",\"`\"%~dp0%filename%`\"\")"
You would replace my example filename with your own on line 2, (taking special care not to touch the closing doublequote). Please note that I have deliberately used a filename of myfile! - 100%% virus free.pdf, to show you that you must double any percent character in your filename, (as the percent character requires special treatment when used in a batch file).
In fact I got my answer after viewing some dos doc. And below is my solution(which is available for open pdf with 'open with' this batch script. To avoid opening the cmd window(it's ugly to my view), I also convert it to a exe using bat2exe converter.
#echo off
set prefix=file:///
set filepath=%~f1
set truepath=%filepath%%filepath:\=/%
start shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge %truepath%
We have a batch file to create a variable from the folder name of the newest folder created in a specific location. As newer versions of this software is released the version number (folder name also) i.e. 10.0, 10.1, 10.2, 10.3 folder is created in this directory. Until now this has worked without hitch, however in the last update they decided to add a folder called Install in this same directory.
Is it possible to change the following script to ignore the Install folder and select the newest created folder name instead:
SET TABVER="C:\Program Files\Tableau\Tableau Server\"
FOR /F "delims=" %%i IN ('dir %TABVER% /b /ad-h /t:c /od') DO SET VERSION=%%i
SET TABCMD="C:\Program Files\Tableau\Tableau Server\%VERSION%\bin\tabcmd.exe"
This batch code could be used:
set "TABVER=C:\Program Files\Tableau\Tableau Server\"
for /F "delims=" %%I in ('dir "%TABVER%" /B /AD-H /T:C /O-D 2^>nul') do if /I not "%%I" == "Install" set "VERSION=%%I" & goto FoundVersion
echo Error: There is no version subfolder in probably not already existing folder:
echo/
echo %TABVER%
echo/
pause
goto :EOF
:FoundVersion
set TABCMD="%TABVER%%VERSION%\bin\tabcmd.exe"
rem Other commands using TABCMD
The DIR option /od is modified to /O-D to get the list of subdirectories in reverse order output by command DIR with newest directory first and oldest directory last.
The additional IF command compares case-insensitive the current directory name with the string Install. Only if the directory name is not Install the directory name is assigned to environment variable VERSION and the loop is exited without processing all other directory names with a jump to label FoundVersion.
I added an error output in case of C:\Program Files\Tableau\Tableau Server does not exist at all, contains no subdirectories or contains just Install and with halting batch file execution until user presses any key and then exiting the batch file processing.
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
See also How to set environment variables with spaces? In general it is better to use the command line set "variable=value" and reference the environment variable with "%variable%" instead of using set variable="value" and reference the environment variable with just %variable%. Look on %TABVER% references why it makes sense not having assigned a folder path with the double quotes to an environment variable.
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.
dir /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
Read also single line with multiple commands using Windows batch file and Where does GOTO :EOF return to?
I have been wanting my script to find a folder that starts with the string "onedrive...".
My code looks like this,
#echo off
set path="C:\Users\%USERNAME%"
if exist %path% (
cd "%path%\onedrive*"
echo %cd%
cd
)
pause
and the output I get is,
C:\Users\310176421\Backupscript\source
C:\Users\310176421\OneDrive for Business
where the first one is my .bat file directory and the second one is the line i want to make into a variable.
Any ideas?
Oh man don't do this, you are overwriting the system PATH. You have to use another name for that variable. And also you have to set it as local.
#echo off
SETLOCAL
REM blah blah
set _my_custom_path=....
ENDLOCAL
Here is a simple batch code which searches in profile directory of current user for a directory starting with string OneDrive and assigns the full path of first found folder without quotes to an environment variable output next before exiting batch.
#echo off
for /F "delims=" %%I in ('dir /AD /B /S "%USERPROFILE%\OneDrive*" 2^>nul') do (
set "OneDriveFolder=%%~I"
goto FoundFolder
)
echo Could not find a folder OneDrive.
goto :EOF
:FoundFolder
echo Found folder: %OneDriveFolder%
set "OneDriveFolder="
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.
dir /?
for /?
goto /?
set /?
Note 1: C:\Users\%USERNAME% is not always equal %USERPROFILE% as the profile directory can be also on another drive than drive C: and Users is just the default parent directory for the user profiles on Windows Vista and later.
Note 2: 2^>nul redirects error message output by command DIR to stdout to device nul which means suppressing the error message in case of no directory starting with OneDrive is found case-insensitive. ^ escapes redirection operator > for command FOR to get 2>nul applied on command DIR.
I'm publishing content to autogenerated folders and after the publishing has finished I want to copy files to that folder based on the foldersname using a batch
The autogenerated folders always have a language name, for example German, Dutch, French and English.
What I want my batch to do is that when the folder name is German it copies all the files from C:\Sourcefolder\DE\ to the new generated folder I'm running the batch from. I've tried to find something myself but my lack of knowledge results in this:
CHDIR /D %1
#ECHO OFF
SETLOCAL
SET "sourcedir=%cd%"
IF "%1"=="German" goto :German
:German
xcopy /Y "C:\Sourcefolder\DE\*.jpg" "%1"
GOTO :EOF
Is there anyone who can help me in the right direction?
Thanks in advance!
Here is the code for a batch file which might do what you want.
#echo off
rem Is this batch file called without any parameter?
if "%~1"=="" (
echo.
echo Run %~nx0 with language as first parameter.
echo.
echo Example: %~nx0 English
echo.
pause
goto :EOF
)
if /I "%~1"=="German" set "ShortName=DE" & goto CopyFiles
if /I "%~1"=="English" set "ShortName=EN" & goto CopyFiles
rem This batch file was called with a (language) string not listed above.
echo.
echo Error: "%~1" is not a supported language.
echo.
pause
goto :EOF
:CopyFiles
rem Copy all JPEG files of the specified language from source folder
rem to the specified language folder in current working directory.
xcopy /H /I /K /Q /R /Y "C:\SourceFolder\%ShortName%\*.jpg" "%~1"
set "ShortName="
Some notes additionally to the comments in the batch code:
%~1 is replaced by cmd.exe on execution of the batch file with the string of first parameter with removing double quotes if batch file was called for example with "English" instead of just English as first parameter.
If you want to know more about %~1 or %~nx0 (name of batch file with extension but without drive and path), open a command prompt window, run there call /? and read help output for this command.
/I option of command if makes the string comparison case-insensitive.
The ampersand in set "ShortName=DE" & goto CopyFiles concatenates the two commands set and goto on a single line which makes it possible here to specify 2 commands for each if without using parentheses. See Conditional Execution for details about this special operator.
For details on the switches used on command xcopy run in a command prompt window xcopy /? and read output help.
By the way: The batch files copies the JPEG files into specified language subfolder of current working directory. The current working directory can be the directory the batch file is stored, but can be also a different directory depending on how batch file was started and from which directory. If you want to make sure that the JPEG files are copied into specified language subfolder of batch file directory, you would need for the line with xcopy:
xcopy /H /I /K /Q /R /Y "C:\SourceFolder\%ShortName%\*.jpg" "%~dp0%~1"
My requirement is - i need to read the filename from an input folder say - C:\Encrypt\In and pass it to the command java.exe -jar D:\SYS\src\PI\IN\Cryptage.jar -rc4 -crypt D:\SYS\src\PI\IN\Decrypt\ D:\src\PI\IN\Encrypt\ %VAR1%%VAR2%
i tried doing the one below - but no luck
set VAR1=FOR /R C:\Encrypt\In %F in (*.*) do echo %~nF
set VAR2=ABCD
echo %VAR1%%VAR2% (concatenate the filename with "ABCD" as constant)
java.exe -jar D:\SYS\src\PI\IN\Cryptage.jar -rc4 -crypt D:\SYS\src\PI\IN\Decrypt\ D:\src\PI\IN\Encrypt\ %VAR1%%VAR2%
(pass it here - so that each time a file comes in the input directory the variables can pick up the file names dynamically through the variables)
echo %VAR1%%VAR2% is not working.
Thanks anyway - i achieved it through this :- cd C:\Encrypt\In\ for %%f in (.) do ( rem echo %%~nfAPSI set v=%%~nfAPSI ) echo %v%
Here is a commented batch code for your task:
#echo off
set "ScanFolder=C:\Encrypt\In"
rem The loop runs command DIR to get a list of files with archive attribute set.
rem Directories are ignored even if archive attribute is set on a directory.
rem On each file with archive attribute currently set the archive attribute
rem is removed from file and then the command is started to process the file.
rem After all files with archive attribute were processed, the batch file
rem waits 5 seconds before scanning the folder again. The loop is infinite
rem and can be breaked only by pressing Ctrl+C or closing command prompt
rem window to stop command line interpreter.
:Loop
for /F "delims=" %%F in ('dir /AA-D /B "%ScanFolder%" 2^>nul') do (
%SystemRoot%\System32\attrib.exe -A "%ScanFolder%\%%~nxF"
java.exe -jar D:\SYS\src\PI\IN\Cryptage.jar -rc4 -crypt D:\SYS\src\PI\IN\Decrypt\ D:\src\PI\IN\Encrypt\ "%ScanFolder%\%%~nxF"
)
%SystemRoot%\System32\ping.exe -n 6 127.0.0.1>nul
goto Loop
java.exe should be called with full path enclosed in double quotes if possible as in this case command line interpreter would not always need to search for it in the folders of environment variable PATH.
Note: The batch file calls the new file with full path, file name and extension without anything appended. Of course you can replace %%~nxF at end of line calling java.exe also with %%~nFABCD if this is necessary in your environment.
For an explanation of the used commands and how they work in detail open a command prompt window and execute following commands to see the help of those commands:
attrib /?
dir /?
for /?
ping /?