How can I within Windows command prompt list all files that are contained in that directory and all subdirectories but the list should only contain a list of files and not the directory location that each file is found in?
Example:
dir /d /s /b /q *.txt will get a list of all text files in all directories so I will end up with c:\example1.txt c:\folder1\example2.txt but I need only the list to show example1.txt example2.txt I hope my question is understandable. just a list of files not showing their paths?
You can try with this command in PowerShell
dir *.txt -r | % Name
From cmd you can execute like
PowerShell -Command "dir *.txt -r | % Name"
There can be used in a Windows command prompt window:
for /R %I in (*.txt) do #echo %~nxI
That results in searching recursive because of option /R in current directory and all its subdirectories for non-hidden files of which long or short 8.3 file name is matched by the wildcard pattern *.txt. Output is just the file name with extension.
Run in a command prompt window for /? to get output the help of the Windows command FOR.
There can be used in a command prompt window also:
for /F "delims=" %I in ('dir *.txt /A-D /B /S 2^>nul') do #echo %~nxI
This command line starts in background one more cmd.exe with option /c to execute the command line enclosed in ' appended as additional arguments. So there is executed in background:
C:\Windows\System32\cmd.exe /c dir *.txt /A-D /B /S 2>nul
The command DIR searches now
in current directory and all its subdirectories because of option /S
for just files because of option /A-D (all attributes except directory attribute) including also hidden files
of which long or short 8.3 name is matched by the wildcard pattern *.txt.
There is output to handle STDOUT of background command process just the list of found file names in bare format because of option /B with full path because of option /S.
It is possible that DIR does not find any file system entry matched by the criteria which results in an error message output to handle STDOUT. This error message is redirected with 2>nul to the device NUL to suppress it.
Read the Microsoft documentation 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.
The output list of fully qualified file names is captured by cmd.exe being opened as Windows command prompt and processed by FOR after cmd.exe started in background closed itself. So it can take some time until there is something displayed in the command prompt window depending on how much file system entries must be searched for by the command DIR of background command process.
FOR would split up by default each line into substrings using normal space and horizontal tab as string delimiters. This line splitting behavior is not wanted here and therefore the option delims= is used to define an empty list of string delimiters to turn off the line splitting. So each file name is assigned one after the other to the specified loop variable I.
The command ECHO outputs finally the file name assigned to loop variable I with just name and extension.
Run in the command prompt window also dir /? for help on this internal command of the Windows Command Processor.
I didnt succeed writing an approriate batch file and would appreciate some help.
Let's say I have an exe in D:\Test\ called script.exe.
To execute this script.exe it requires an additional argument of a .bin files (e.g. bin01.bin, bin02.bin).
Therefore it would be like: script.exe -i bin01.bin, script.exe -i bin01
I want the script to execute with all .bin files from all subfolders
D:\Test\script.exe
D:\Test\Folder01\bin01.bin
D:\Test\Folder01\bin02.bin
D:\Test\Folder02\bin01.bin
D:\Test\Folder03\bin01.bin
anyone could help me here?
Thanks a lot in advance.
For direct execution from within a command prompt window:
for /R "D:\Test" %I in (*.bin) do #D:\Test\script.exe -i "%I"
And the same command line for usage in a batch file:
#for /R "D:\Test" %%I in (*.bin) do #D:\Test\script.exe -i "%%I"
The command FOR searches recursive in directory D:\Test and all subdirectories for files matching the wildcard pattern *.bin.
The name of each found file is assigned with full path to case-sensitive loop variable I.
FOR executes for each file the executable D:\Test\script.exe with first argument -i and second argument being the name of found file with full path enclosed in double quotes to work for any *.bin file name even those containing a space or one of these characters: &()[]{}^=;!'+,`~.
# at beginning of entire FOR command line just tells Windows command interpreter cmd.exe not to echo the command line after preprocessing before execution to console window as by default.
# at beginning of D:\Test\script.exe avoids the output of this command to console executed on each iteration of the loop.
Most often the echo of a command line before execution is turned off at beginning of the batch file with #echo off as it can be seen below.
#echo off
for /R "D:\Test" %%I in (*.bin) do D:\Test\script.exe -i "%%I"
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.
echo /?
for /?
I am generating a Windows Batch script to copy a file, only when the source is updated. If the file is updated, I want to delete another file.
The problem is that I can't find a simple way to trigger an event when the file update happens.
I thought of using %ERRORLEVEL% but this gives 0 whether file is copied or not.
I also thought of saving the xcopy output to a text file and then processing the file but this just seems to a little impractical for such a simple task?
Any other Ideas?
Code so far
SET SOURCEFILE=%CD%\source.txt
SET DELFILE=%CD%\toDelete.txt
SET DESTDIR=%WINDIR%\Deployment\
xcopy "%SOURCEFILE%" "%DESTDIR%" /c /d /q /y
REM IF File is updated, delete %DELFILE%
I explain the method used in command line posted by Aacini on entire batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=source.txt"
set "DeleteFile=toDelete.txt"
set "DestinationDirectory=%SystemRoot%\Deployment\"
for /F %%I in ('%SystemRoot%\System32\xcopy.exe "%SourceFile%" "%DestinationDirectory%" /C /D /Q /Y 2^>nul') do set "CopiedFilesCount=%%I"
if %CopiedFilesCount% GTR 0 del "%DeleteFile%"
rem Add here more command lines using one of the 3 environment variables define above.
endlocal
First it is very important on copying a single file with XCOPY that the destination directory path ends with a backslash as otherwise XCOPY would prompt if the destination is a directory or a file.
XCOPY as used here always outputs to handle STDOUT as last line an information message with the number of files being copied at beginning even when nothing is copied or when an error occurred.
The command FOR executing XCOPY in a separate command process in background captures this output to handle STDOUT and processes it line by line.
Empty lines and lines starting with a semicolon are ignored with using the default options as used here with no eol= option. The other lines are processed with splitting each line up into strings separated by spaces or horizontal tabs on using default delimiters as used here because of no delims= option. Because of not using tokens= option just the first space/tab separated string of each line is assigned to loop variable I and the rest of the line is ignored.
The current value of the loop variable I is assigned on each processed line to environment variable CopiedFilesCount replacing its previous value.
The first space/tab separated string on last line output by XCOPY is the number of copied files which is here on copying just a single file either 0 or 1. So finally after FOR loop execution finished the environment variable CopiedFilesCount has either 0 or 1 as value.
The value is compared with GREATER THAN operator of command IF to determine if the file was copied in which case the other file is deleted.
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.
del /?
echo /?
endlocal /?
for /?
if /?
rem /?
set /?
setlocal /?
I'm trying to make my Visual Studio build script execute a .bat file that does something important.
Here is what I'm want to do right now:
cd "F:\- Big Packets -\kitterengine\Common\" Template.bat
But it doesn't work.
I have to do this to make it work:
cd "F:\- Big Packets -\kitterengine\Common\"
F:
Template.bat
But this is pretty difficult to add to the Visual Studio script.
How can I do this in one single line?
"F:\- Big Packets -\kitterengine\Common\Template.bat" maybe prefaced with call (see call /?). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat.
CMD Cheat Sheet
Cmd.exe
Getting Help
Punctuation
Naming Files
Starting Programs
Keys
CMD.exe
First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.
For help on starting CMD type cmd /?. You must start it with either the /k or /c switch unless you just want to type in it.
Getting Help
For general help. Type Help in the command prompt. For each command listed type help <command> (eg help dir) or <command> /? (eg dir /?).
Some commands have sub commands. For example schtasks /create /?.
The NET command's help is unusual. Typing net use /? is brief help. Type net help use for full help. The same applies at the root - net /? is also brief help, use net help.
References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.
WMIC is a multipurpose command. Type wmic /?.
Punctuation
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
2>&1 Redirects command error output to the same location as command output.
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatenate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0
is the batchfile's name.
%* (%*) the entire command line.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop.
Single % sign at command prompt and double % sign in a batch file.
\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
. (win.ini) the LAST dot in a file path separates the name from extension
. (dir .\*.txt) the current directory
.. (cd ..) the parent directory
\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off.
Naming Files
< > : " / \ | Reserved characters. May not be used in filenames.
Reserved names. These refer to devices eg,
copy filename con
which copies a file to the console window.
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4,
COM5, COM6, COM7, COM8, COM9, LPT1, LPT2,
LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
CONIN$, CONOUT$, CONERR$
--------------------------------
Maximum path length 260 characters
Maximum path length (\\?\) 32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length 255 characters
Starting a Program
See start /? and call /? for help on all three ways.
There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.
If a full path isn't given then Windows looks in
The directory from which the application loaded.
The current directory for the parent process.
Windows NT/2000/XP: The 32-bit Windows system directory. Use the
GetSystemDirectory function to get the path of this directory. The
name of this directory is System32.
Windows NT/2000/XP: The 16-bit Windows system directory. There is no
function that obtains the path of this directory, but it is
searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get
the path of this directory.
The directories that are listed in the PATH environment variable.
Specify a program name
This is the standard way to start a program.
c:\windows\notepad.exe
In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
Start starts programs in non standard ways.
start "" c:\windows\notepad.exe
Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.
Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try
start shell:cache
Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.
Also note the first set of quotes, if any, MUST be the window title.
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.
Other Filenames
Typing a non program filename is the same as double clicking the file.
Keys
Ctrl + C exits a program without exiting the console window.
For other editing keys type Doskey /?.
↑ and ↓ recall commands
ESC clears command line
F7 displays command history
ALT+F7 clears command history
F8 searches command history
F9 selects a command by number
ALT+F10 clears macro definitions
Also not listed
Ctrl + ←or→ Moves a word at a time
Ctrl + Backspace Deletes the previous word
Home Beginning of line
End End of line
Ctrl + End Deletes to end of line
Can refer to here: https://ss64.com/nt/start.html
start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat
There are many possibilities to solve this task.
1. RUN the batch file with full path
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after #echo off as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.
Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.
2. CALL the batch file with full path
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
3. Change directory and RUN batch file with one command line
There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the && operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.
4. Change directory and CALL batch file with one command line
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat.
5. Change directory and CALL batch file with keeping current environment with one command line
The four solutions above change the current directory and it is unknown what Template.bat does regarding
current directory
environment variables
command extensions state
delayed expansion state
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.
Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.
ONE MORE NOTE
If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.
You can use Cmd command to run Batch file.
Here is my way =>
cmd /c ""Full_Path_Of_Batch_Here.cmd" "
More information => cmd /?
Like Linux, to run the myapp.exe, you can use only one of these three methods.
use system path
add project directory to your systeme path, then:
myapp.exe
or
myapp
use full long path
\path\to\project\myapp.exe
go to working directory
cd \path\to\project
.\myapp.exe
I have written the following .bat file, and it runs perfectly on my Windows 2000 machine, but will not run on my Windows 7 or Windows XP machines. Basically it just loops through the current directory and runs a checksum program which returns the checksum. The output of the program is saved to a text file and then formatted to remove the checksum of the output file.
#Echo Off
for /r %%f in (*.txt) do crc32sum.exe %%f >> all_checksums.txt
ren all_checksums.txt old.txt
findstr /v /e /c:"all_checksums.txt" old.txt > all_checksums.txt
del old.txt
When I run this file on my Win2k PC with a bunch of text files and the crc32sum.exe in a folder, it outputs the file. On other machines it outputs a blank file. I turned Echo on and kept only the for loop line and found that the output from executing the crc32sum.exe is nothing. If you manually run the crc32sum.exe file it outputs the checksum no problem.
Any ideas as to how to fix this?
EDIT: Here is a link to the software: http://www.di-mgt.com.au/src/digsum-1.0.1.zip
EDIT2: New development, it seems that the file works if the path of the folder has no spaces in it i.e. C:\temp or C:\inetpub\ftproot or C:\users\admin\Desktop\temp. Does anyone know how I can make this work with paths that have spaces? %%~f doesnt work it says unexpected.
Try this modified batch code which worked on Windows XP SP3 x86:
#echo off
goto CheckOutput
rem Command DEL does not terminate with an exit code greater 0
rem if the deletion of a file failed. Therefore the output to
rem stderr must be evaluated to find out if deletion was
rem successful or (for a single file) the file existence is
rem checked once again. For details read on Stack Overflow
rem the answer http://stackoverflow.com/a/33403497/3074564
rem The deletion of the file was successful if file created
rem from output message has size 0 and therefore the temp
rem file can be deleted and calculation of the CRC32 sums
rem can be started.
:DeleteOutput
del /F "all_checksums.txt" >nul 2>"%TEMP%\DelErrorMessage.tmp"
for %%E in ("%TEMP%\DelErrorMessage.tmp") do set "FileSize=%%~zE"
if "%FileSize%" == "0" (
set "FileSize="
del "%TEMP%\DelErrorMessage.tmp"
goto CalcCRC32
)
set "FileSize="
echo %~nx0: Failed to delete file %CD%\all_checksums.txt
echo.
type "%TEMP%\DelErrorMessage.tmp"
del "%TEMP%\DelErrorMessage.tmp"
echo.
echo Is this file opened in an application?
echo.
set "Retry=N"
set /P "Retry=Retry (N/Y)? "
if /I "%Retry%" == "Y" (
set "Retry="
cls
goto CheckOutput
)
set "Retry="
goto :EOF
:CheckOutput
if exist "all_checksums.txt" goto DeleteOutput
:CalcCRC32
for /R %%F in (*.txt) do (
if /I not "%%F" == "%CD%\all_checksums.txt" (
crc32sum.exe "%%F" >>"all_checksums.txt"
)
)
The output file in current directory is deleted if already existing from a previous run. Extra code is added to verify if deletion was successful and informing the user about a failed deletion with giving the user the possibility to retry after closing the file in an application if that is the reason why deletion failed.
The FOR command searches because of option /R recursive in current directory and all its subdirectories for files with extension txt. The name of each found file with full path always without double quotes is hold in loop variable F for any text file found in current directory or any subdirectory.
The CRC32 sum is calculated by 32-bit console application crc32sum in current directory for all text files found with the exception of the output file all_checksums.txt in current directory. The output of this small application is redirected into file all_checksums.txt with appending the single output line to this file.
It is necessary to enclose the file name with path in double quotes because even with no *.txt file containing a space character or one of the special characters &()[]{}^=;!'+,`~ in its name, the path of the file could contain a space or one of those characters.
For the files
C:\Temp\test 1.txt
C:\Temp\test 2.txt
C:\Temp\test_3.txt
C:\Temp\TEST\123-9.txt
C:\Temp\TEST\abc.txt
C:\Temp\TEST\hello.txt
C:\Temp\TEST\hellon.txt
C:\Temp\Test x\test4.txt
C:\Temp\Test x\test5.txt
the file C:\Temp\all_checksums.txt contains after batch execution:
f44271ac *test 1.txt
624cbdf9 *test 2.txt
7ce469eb *test_3.txt
cbf43926 *123-9.txt
352441c2 *abc.txt
0d4a1185 *hello.txt
38e6c41a *hellon.txt
1b4289fa *test4.txt
f44271ac *test5.txt
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.
cls /?
del /?
echo /?
for /?
goto /?
if /?
rem /?
set /?
type /?
One of the help pages output on running for /? informs about %~I, %~fI, %~dI, %~pI, %~nI, %~xI, %~sI, %~aI, %~tI, %~zI.
Using in a batch file f (in lower case) as loop variable and referencing it with %%~f is a syntax error as command processor expects next the loop variable. %%~ff would be right, but could be different to %%~fI (name of a file/folder with full path and extension without quotes) in comparison to %%~I (string without surrounding quotes).
It is not advisable to use (those) small letters as loop variable. It is better to use upper case letters or character # as loop variable. The loop variable and also those modifiers are case sensitive while nearly everything else in a batch file is case insensitive.