Call MSXSL from batch file - batch-file

I want to create a batch file that loops through a folder containing xml files, then call msxsl to modify them and after modify the xml file, copying to another folder with original filename.
I tried this:
forfiles /p C:\Users\mae\Documents\Testing\MSXSL\In /m *.xml /c "cmd /c C:\Users\mae\Documents\Testing\MSXSL\msxsl.exe #file pre-process_add_filename.xsl -o C:\Users\mae\Documents\Testing\MSXSL\Out\#file"
But that gives me this error:
Error occurred while creating file 'C:\Users\mae\Documents\Testing\MSXSL\Out\"bk_OIOUBLInvoice_TEST.xml"'.
Code: 0x8007007b
The filename, directory name, or volume label syntax is incorrect.
This is because of the double quotes around the output filname. How do I get around this?

As already suggested by others in comments, you should use a standard for loop for your task rather than forfiles:
for %%I in ("%UserProfile%\Documents\Testing\MSXSL\In\*.xml") do (
"%UserProfile%\Documents\Testing\MSXSL\msxsl.exe" "%%I" "pre-process_add_filename.xsl" -o "%UserProfile%\Documents\Testing\MSXSL\Out\%%~nxI"
)
But if you do insist on forfiles you could use the following code:
forfiles /P "%UserProfile%\Documents\Testing\MSXSL\In" /M "*.xml" /C "cmd /C for %%I in (#file) do 0x22%UserProfile%\Documents\Testing\MSXSL\msxsl.exe0x22 #file 0x22pre-process_add_filename.xsl0x22 -o 0x22%UserProfile%\Documents\Testing\MSXSL\Out\%%~I0x22"
The inner for loop together with the ~-modifier is used to get rid of the additional quotation marks around the file name returned by #file. The term 0x22 is forfiles-specific and marks a literal quotation mark.

Related

Moving hl7 files in server with batch script

I'm trying to move hl7 files older then 7 days. My script is
forfiles /p C:\TEST /m *.hl7* /s /d -30 /c "cmd /c move #file C:\New Folder"
pause
I'm getting error like
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
Any help? please.
This is because New Folder has a space in it and forfiles doesn't know how to handle that.
Normally, you'd put paths with spaces in quotes to tell cmd that everything inside of the quotes should be considered a single item. Unfortunately, the entire "cmd /c move #file C:\New Folder" is already in quotes, so adding more quotes inside of those quotes is only going to make things worse. The good news is that in forfiles /?, there's a line that reads
To include special characters in the command line, use the hexadecimal code for the character in 0xHH format (ex. 0x09 for tab). Internal CMD.exe commands should be preceded with "cmd /c".
The hexadecimal version of " is 0x22, and if you change your command to forfiles /p C:\TEST /m *.hl7 /s /d -7 /c "cmd /c move #file 0x22C:\New Folder0x22", then your script will work correctly.

CMD to delete a specific folder with files from multiple folder paths

I need a CMD batch file to delete all the log files.
My company makes plugins for their product and the path is something as follows:
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log-archive
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log-archive
Now I need to delete all the log and log-archive folders with its contains.
Currently I wrote a samll program like this:
#echo off
color 02
for %%A in (
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log-archive"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log-archive"
) do (
del /Q %%A
echo Deleted %%A
)
echo All files deleted
pause
echo Program ended
But here I need to insert all the log paths manually.
I am looking for a solution where I could point the parent folder (say Program Files/Company) and it could traverse all the files inside and will delete all the log and log-archival folders with its contains.
I am a QA person have good QA experience but no experience on batch programming and I dont have much time and support team is not present. [Need help]. There are more than 1K log files are present.
First, as explained by the Microsoft documentation Naming Files, Paths, and Namespaces, the directory separator on Windows is \ and not / as on Linux/Mac. / is used on Windows for options as you can see on your code for example on /Q. So use in future \ in file/folder paths. The Windows file system accessing kernel functions automatically replace all forward slashes by backslashes before accessing the file systems, but writing code depending on automatic error correction is never a good idea.
The task to delete all folders with name log or log-archive in a specified folder and all its subfolders can be done with a single command line.
#for /F "delims=" %%I in ('dir "%ProgramFiles%\product\plugins\plugin_Path\log*" /AD /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /E /I /R "\\log \\log-archive"') do #rd /Q /S "%%I" 2>nul
FOR with option /F runs in a separate command process started with cmd.exe /C (more precise with %ComSpec% /C) in background the command line in '... ' which is here:
dir "C:\Program Files\product\plugins\plugin_Path\log*" /AD /B /S 2>nul | C:\Windows\System32\findstr.exe /E /I /R "\\log \\log-archive"
The command DIR outputs to handle STDOUT
in bare format because of option /B
just directories because of option /AD (attribute directory)
directory names matching the wildcard pattern log*
in specified directory C:\Program Files\product\plugins\plugin_Path
and all its subdirectories because of option /S
with full path also because of option /S.
It could be that DIR does not find any file system entry matching these criteria. In this case an error message is output by DIR to handle STDERR. This error output is redirected with 2>nul to device NUL to suppress it.
The standard output of DIR is redirected with | to handle STDIN of FINDSTR which runs
because of option /I a case-insensitive
regular expression find explicitly requested with option /R
for string \log or \log-archive (space is interpreted as OR)
which must be found at end of a line because of option /E.
All lines matching these search criteria are output by FINDSTR to handle STDOUT of background command process. This filtering of output of DIR with FINDSTR is necessary to avoid the deletion of a directory which is named for example LogToKeep also found and output by DIR.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F captures output to handle STDOUT of started command process and processes this output line by line after started cmd.exe terminated itself. Empty lines are always ignored by FOR which do not occur here. Lines starting with a semicolon are also ignored by default because of eol=; is the default definition for end of line option. But a full qualified folder path cannot contain a semicolon at beginning because the folder path starts either with a drive letter or with a backslash in case of a UNC path. So default end of line option can be kept in this case. FOR would split up by default every line into substrings with using normal space and horizontal tab as string delimiters and would assign just first space/tab separated string to specified loop variable. This line splitting behavior is not wanted here as the folder path contains definitely a space character and the entire folder path is needed and not just the string up to first space. For that reason delims= is used to specify an empty list of delimiters which disables line splitting behavior.
FOR executes for every directory output by DIR passing FINDSTR filter with full path the command RD to remove the directory quietly because of option /Q and with all files and subdirectories because of /S.
The deletion of the directory could fail because of missing NTFS permissions, or the directory to delete or one of its subdirectories is current directory of a running process, or a file in the directory to delete is currently opened by a running process in a manner which denies deletion of the file while being opened, or the directory to delete does not exist anymore because it was deleted already before in FOR loop. The error message output by command RD to handle STDERR is in this case redirected to device NUL to suppress it.
Please note that command RD deletes all log and log-archives directories and not just the files and subdirectories in these directories. It is unclear from your question what exactly should be deleted by the batch file.
It is of course also possible to replace rd /Q /S "%%I" by del /A /F /Q "%%I\*" to delete just all files including hidden and read-only files quietly in the directory assigned with full path to loop variable I.
# left to command FOR and command RD just suppress the output of those commands before execution by Windows command processor cmd.exe. Both # are not needed if this single command line is used in a batch file containing before #echo off.
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 /?
dir /?
findstr /?
for /?
rd /?
If you're wanting to remove the contents of the log and log-archive directories. This means the easiest solution would probably be FORFILES.
This will delete all the files under log and log-archive directories found within any subfolder of "C:\Program Files\product\plugins". The folders MUST be named exactly log or log-archive. It will not remove directories.
FORFILES /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
You could also add a /D switch to only delete applicable files if they are older than a specific number of days. This will delete all the log and log-archive files under "C:\Program Files\product\plugins" that are older than 90 days:
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"

Find Specific *.exe files in directories and run the app with parameters

I'm trying to find recursively all "MyApp.exe" apps in "C:\Builds" folder and run the apps with "createdatabase closeimmediately" arguments/parameters.
What I search so far:ForFiles Microsoft docs
Here is the forfiles pattern:
forfiles [/p <Path>] [/m <SearchMask>] [/s] [/c "<Command>"] [/d [{+|-}][{|}]]
Here is what I have:
forfiles /p c:\Builds /s /m MyApp.exe /c "cmd /c start #path" "createdatabase closeimmediately"
If I run above script, it is showing error:
ERROR: Invalid argument/option - 'createdatabase closeimmediately'.Type "FORFILES /?" for usage.
If I run without parameteres, it finds apps correctly and runs, but I need to run with parameters:
forfiles /p c:\Builds /s /m MyApp.exe /c "cmd /c start #path"
How can I run apps with parameters in ForFiles?
I know this was mentioned in the comments, but the comments are becoming too long for me to post a decent comment still, so here is an answer. This should do exactly what you want, it will recursively search for the file and execute if exists.
#echo off
for /r "c:\Builds" %%i in (myapp.exe) do if exist "%%i" "%%i" createdatabase closeimmediately
a slightly different way, find all executables, and launch if the name matches myapp.exe:
for /r "c:\Builds" %%i in (*.exe) do if /I "%%~nxi" == "myapp.exe" "%%I" createdatabase closeimmediately
There are multiple methods possible to search for MyApp.exe in C:\Build and all subfolders and execute the found executable with the two parameters createdatabase and closeimmediately.
The first solution uses command FOR to search for any file matching the wildcard pattern MyApp*.exe in C:\Build and any non-hidden subfolder.
For usage in a batch file:
for /R "C:\Build" %%I in ("MyApp*.exe") do if /I "%%~nxI" == "MyApp.exe" "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /R "C:\Build" %I in ("MyApp*.exe") do #if /I "%~nxI" == "MyApp.exe" "%I" createdatabase closeimmediately
It is necessary that the string inside the round brackets contains at least one * or ? to define a wildcard pattern. Otherwise FOR would not search for files with name MyApp.exe on using just "MyApp.exe" in C:\Build and all its subfolders. It would simply append the string "MyApp.exe" (with the double quotes) to folder path of every folder found in C:\Build folder structure and would assign folder path + "MyApp.exe" to loop variable I and execute the command line referencing the loop variable.
The IF condition is used to make sure that only MyApp.exe is executed and not for example MyAppOther.exe found by chance also by FOR with wildcard pattern MyApp*.exe. The string comparison is done case-insensitive because of /I.
It would be also possible to use a different wildcard pattern like MyApp.exe*. This could reduce the number of false positives. But for security the IF condition should be nevertheless used.
The second solution is using just MyApp.exe and check if a file with that name really exists in the given folder path before executing it.
For usage in a batch file:
for /R "C:\Build" %%I in (MyApp.exe) do if exist "%%I" "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /R "C:\Build" %I in (MyApp.exe) do #if exist "%I" "%I" createdatabase closeimmediately
MyApp.exe is specified in round brackets without being enclosed in " as otherwise the string assigned to loop variable I would be for example C:\Build\"MyApp.exe" and not C:\Build\MyApp.exe. By automatic error correction the string value C:\Build\"MyApp.exe" might also work depending on which string is really used instead of MyApp.exe. But this is not really a safe method and does not work if the string MyApp.exe contains a space, comma, semicolon, or other characters like &()[]{}^=;!'+,`~.
The third solution is using the command DIR for searching for MyApp.exe without a wildcard pattern to find only files with exactly that name and let FOR execute the found executables with that name.
For usage in a batch file:
for /F "delims=" %%I in ('dir "C:\Build\MyApp.exe" /A-D-H /B /S 2^>nul') do "%%I" createdatabase closeimmediately
For usage in command prompt window:
for /F "delims=" %I in ('dir "C:\Build\MyApp.exe" /A-D-H /B /S 2^>nul') do #"%I" createdatabase closeimmediately
In comparison to FOR the command DIR really searches for files with name MyApp.exe even on argument string not containing a wildcard character like * or ?.
FOR executes the DIR command line in a separate command process started with cmd.exe /C in background and captures everything written to handle STDOUT of this command process.
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.
2>nul is used to suppress the error message output by DIR to handle STDERR by redirecting it to device NUL if no file MyApp.exe could be found in C:\Build or its subdirectories.
DIR outputs because of /B and /S just the full qualified file name, i.e. file path + file name + file extension, of every found MyApp.exe line by line.
FOR processes the captured output line by line with skipping empty lines and lines starting with a semicolon. Such lines are surely not output by DIR with the used options.
FOR would also split up each line into substrings (tokens) on spaces/tabs and would assign only first substring to loop variable I. This string splitting behavior is not wanted here as a folder name could contain one or more spaces. For that reason FOR option delims= is used to define an empty list of delimiters which disables the line splitting behavior.
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 /?
if /?

Bug in `forfiles`, wrong expansion of `#file` variable?

Using the forfiles batch command, sometimes the #path variable and the #file variable are the same, and sometimes they are different. This looks like a bug to me.
To illustrate - setup:
md test_subfolder
echo Hello>test_subfolder\test.txt
Now #path and #file are different, like you would expect:
forfiles /p test_subfolder /c "cmd /c echo CD: [%cd%] PATH: [#path] FILE: [#file]"
That yields:
CD: [D:\] PATH: ["D:\test_subfolder\test.txt"] FILE: ["test.txt"]
Now, try overwriting the file using #path. This does what you would expect.
forfiles /p test_subfolder /c "cmd /c echo Goodbye>#path"
type test_subfolder\test.txt
Result:
Goodbye
Trying the same thing using #file instead of #path:
forfiles /p test_subfolder /c "cmd /c echo Farewell>#file"
This should create a new file in the root, and leave the file in the subfolder unchanged. But instead, it behaves the same way that the #path does.
Checking for the file in the root folder:
dir test.txt
Result:
Volume in drive D is Recovery
Volume Serial Number is AE9D-4134
Directory of D:\
File Not Found
Looking in the subfolder:
type test_subfolder\test.txt
Result:
Farewell
This is using Windows 7 Professional - I don't know how it might work in other versions.
How can I get #file to behave the way I expect?
This is not a bug. The real problem is the point where the parser expands %CD%, it is done immediately, so you see the current directory of the cmd instance you are working in.
The cmd instance opened by forfiles receives the path provided at /p as the current directory. To see this, change the command line to:
forfiles /p test_subfolder /c "cmd /c echo CD: [0x25cd0x25] PATH: [#path] FILE: [#file]"
0x25 represents the hex. code of the % sign, so expansion of %cd% is not done immediately, but transferred to the "inner" cmd instance.
This will show you that the echo command is actually executed in D:\test_subfolder and so the #file variable expansion of forfiles behaves correctly. Hence the output will be:
CD: [D:\test_subfolder] PATH: ["D:\test_subfolder\test.txt"] FILE: ["test.txt"]
This explains why your line of code forfiles /p test_subfolder /c "cmd /c echo Farewell>#file", when executed in D:\, (over-)writes the file D:\test_subfolder\test.txt rather than creating a new file D:\test.txt.
Hm ... this works! It's a mystery to me why, though.
forfiles /p test_subfolder /c "cmd /c echo So Long>%CD%#file"
type test.txt
Result:
So Long
forfiles /p test_subfolder /c "cmd /c echo So Long>%CD%\#file" command is working for me,[please note that i have used "\" after %CD%] , you need write to a file in the sub directory , you are trying to execute the above command outside the sub folder , probabaly that might me the reason you are feeling the difference between #path and #file

How to copy all files created between two dates using Command prompt?

I have written code in window batch file (eq. getFiles.bat ) that get all files within select date range.
eq.
xcopy /S /D:01-10-2011 *.* C:\todaysFiles
But I want get all files in between two dates including From date and To date.
file extension is .cmd or .bat
If you're on Vista/Win7/WinServer2008 you can use robocopy like so:
robocopy c:\source c:\destination *.* /MAXAGE:20101231 /MINAGE:20111001
On XP, I'm not sure if there are built-in solutions short of using Powershell and the like.
The title of this question is slightly misleading. Based on the questioner's xcopy example, I believe the questioner wants to know "How to copy all files created...", not how to get all files (which I equate with list).
The questioner also states "file extension is .cmd or .bat". This could mean that the questioner wants to copy only files with these extensions but I think it means the questioner would like a batch script solution.
To use the following solution, open a command prompt and chdir to the folder where the files to be copied are located. Then enter the commands listed below, changing the SET values as appropriate.
SET DESTINATION=C:\destination
SET DATE_FROM=01/01/2005
SET DATE_TO=01/01/2007
> nul forfiles /S /D +%DATE_FROM% /C "cmd /C if #isdir==FALSE 2> nul forfiles /M #file /D -%DATE_TO% && > con ( echo #path && copy /V #path %DESTINATION% )"
Note: this will copy files in subfolders as well as files in the top-level folder.
The SET values could be hard-coded directly into the > nul forfiles... line, meaning only one line is required, but for clarity I've used variable substitution.
A caveat is that it is based on date modified (original question asked for date created)
Credit to aschipfl (https://stackoverflow.com/a/36585535/1754517) for providing the inspiration for my answer.
You can also use the forfiles command. It can search recursively in all subfolders /s for files created in the selected root folder /p <Path>, execute commands on the selected files /c "<Command>", apply masks to search /m <SearchMask>, between a date range /d [{+|-}][{<Date>|<Days>}]
more info here, and here
Here's a batch for viewing files by creation date by year. Easily changed to cmd prompt by removing the extra percentage symbols.
for %%a in (2011 2012 2013 2014 2015 2016 2017) do (
for /f %%i in ('xxcopy i:\podcasts\*.* /LL /ZS /Q /FC /DA:%%a-01-01 /DB:%%a-12-31 ^| find /c /v ""') do echo %%a: %%i
)

Resources