Trouble with renaming folders and sub folders using Batch - windows

So I'm trying to set up a template file structure for projects that can be modified in name to suit each project. I have created the example directory containing example folders i.e. "Template project" contains "template hardware" , "template software" etc. , and have a simple batch program that copies the "template project" folder and all contained subfolders, however I would like to change the word 'template' with what ever I choose to call the project. I was wondering if this is possible to do? Ideally I could just edit the batch file with the name of the project and then run it to copy the template and rename it.
Any help is greatly appreciated!

To start learning type help at the command prompt. Then anything on that list add /? for more help.
Set /p NewName=Enter project name
md "c:\somewhere\%newname%project\%newname% software
md "c:\somewhere\%newname%project\%newname% hardware
or use xcopy (and use/l to have it do a test without copying)
xcopy "c:\tempate" "d:\%newname%" /e /h /q /i /c
See set /?, md /?, and xcopy /?. Type just set to see a list of variables.
& 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
| 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 concatinate 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.
%<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 seperates 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.
< > : " / \ | 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.
Specify a program name
--------------------------------
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 "" 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
Use Call command
-------------------------
Call is used to start batch files and wait for them to exit and continue the current batch file.
.
--

Related

How to loop through folder names and move folders based on date in folder name?

I currently have a batch file that loops through a text file which has a list of file names and moves these files to folders based on the date in the file name.
I'm trying now to change this to do something similar but for folders. Get folder names and then move each folder to another location based on the date in the folder name.
Example of folder structure:
Before move:
k:\PLPR1
k:\PLPR1\20210910\data
k:\PLPR1\20210909\data
k:\PLPR1\20210830\data
After move:
l:\PLPR1\2021\FTP Data\September\10 September\data
l:\PLPR1\2021\FTP Data\September\09 September\data
l:\PLPR1\2021\FTP Data\September\30 August\data
The folder moving task can be done with following batch file:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SourcePath=K:\PLPR1"
set "TargetPath=L:\PLPR1"
set "Month01=January"
set "Month02=February"
set "Month03=March"
set "Month04=April"
set "Month05=May"
set "Month06=June"
set "Month07=July"
set "Month08=August"
set "Month09=September"
set "Month10=October"
set "Month11=November"
set "Month12=December"
for /F "delims=" %%I in ('dir "%SourcePath%" /AD-L /B 2^>nul') do (
set "FolderName=%%I"
set "Year=!FolderName:~0,4!"
set "Month=!FolderName:~4,2!"
set "Day=!FolderName:~6,2!"
for %%I in (Month!Month!) do set "Month=!%%I!"
%SystemRoot%\System32\robocopy.exe "%SourcePath%\%%I" "%TargetPath%\!Year!\FTP Data\!Month!\!Day! !Month!" /E /MOVE /NDL /NFL /NJH /NJS /R:1 /W:5 >nul
)
endlocal
The first two command lines define the required execution environment which is:
command echo mode turned off
command extensions enabled
delayed environment variable expansion enabled
The enabled delayed expansion means that this batch file cannot be used without modification on source or target path containing one or more exclamation marks.
It is further expected by this batch file code that the source folder contains only subfolders with names being the date in format yyyyMMdd.
The usage of for /F with a command line enclosed in ' results in running in background one more cmd.exe with option /c and the specified command line appended as additional arguments. So executed is in background with Windows installed to C:\Windows:
C:\Windows\System32\cmd.exe /c dir "K:\PLPR1" /AD-L /B 2>nul
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 command DIR searches
in specified directory for file system entries which
have the directory attribute set and are not reparse points (directory junctions) because of option /AD-L and
outputs in bare format just the names of the folders because of option /B without path.
The error message output by DIR on not finding any directory is suppressed by redirecting it to device NUL.
The output of DIR to handle STDOUT of background command process is captured by FOR respectively cmd.exe processing the batch file and processed line by line after started cmd.exe closed itself after finishing execution of DIR.
FOR with option /F results in always ignoring empty lines which do not occur here at all. A non-empty line would be split up by default into substrings using normal space and horizontal tab as string delimiters. That line splitting behavior would be no problem here as the folder names in format yyyyMMdd do not contain a space character, but there is nevertheless used delims= to define an empty list of string delimiters which makes the processing of the file names a very little bit faster as line splitting behavior is turned off in this case.
If the first substring being now the entire directory name would start with a semicolon, FOR would also ignore the captured line for further processing. This end of line behavior does not matter here as the directory names do not start with a semicolon.
So there is in memory of the command process processing the batch file now a list of directory names which are assigned one after the other to the specified loop variable I and it does not matter anymore what happens next in the source directory during the loop iterations. This is important, especially if the source directory is on a FAT drive (FAT32, exFAT).
The directory name without path is assigned to an environment variable and substitutions are used next with delayed expansion to split the date in name up to year, month and day in month.
There are defined twelve environment variables which hold for each month with two digit month value at end of the variable name the appropriate name of the month. A simple FOR loop is used to concatenate the fixed string Month with the month value determined from directory name do redefine the environment variable Month using delayed expansion by the month name assigned to the dynamically built environment variable name starting with Month and ending with current month value.
Now all required data are available to move everything inside the current directory with ROBOCOPY to the appropriate destination directory using the year, month and day values. ROBOCOPY creates automatically the entire destination (target) directory tree.
It is of course possible that ROBOCOPY fails to delete a file/directory in source directory, for example if a file is currently opened in source directory by another application or a directory is the current directory of a running process. But that does not matter for the FOR loop as the command FOR itself does not access anymore the file system to get next directory name because of processing a list of directory names in memory of the command process. So it is not possible that any directory is processed more than once, or that a directory is skipped by chance, or the FOR loop runs into an endless loop thanks to first getting the list of directories to process loaded into memory.
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 /?
echo /?
endlocal /?
for /?
robocopy /?
set /?
setlocal /?

Batch script to rename all files with spaces [duplicate]

This question already has answers here:
Variables are not behaving as expected
(1 answer)
Example of delayed expansion in batch file
(5 answers)
At which point does `for` or `for /R` enumerate the directory (tree)?
(1 answer)
Closed 1 year ago.
I'm trying to write a batch script that'll read all the pdf files in a folder and rename them such that there are no spaces in them. So I've typed up the below code. Although most of the parts of the code seems to work in isolation, I get an error when running the code together.
for /r %%f in (*.txt) do (
set filename=%%~nxf
set new=%filename: =%
ren "%filename%" %new%
)
The filename is detected correctly by line2. But on line3, I don't get the value I've stored in line2. Interestingly enough, if I were to run the command again in the same prompt, line3 then works (filename variable is read correctly). It must be how the for loop operates in a batch script. If I run the below code exactly 3 times in the same command prompt, the code works perfectly fine (I assume because all variables are now set correctly). Can someone please help point me in the right direction? Thanks in advance.
Note: I have a filename called "filename .txt" in the working directory, which I realise wasn't the best choice of filename. :|
(error in screenshot)
Open a command prompt, run set /? and read the output help carefully and completely from top of first to bottom of last page, especially the section about delayed expansion explained also by Variables are not behaving as expected. The Windows command processor cmd.exe processes the entire command block starting with ( and ending with matching ) before executing command FOR at all. All environment variables using %...% syntax are expanded (replaced) already during this processing phase by the appropriate variable expansion result.
So executed is the following on environment variable filename not already defined:
for /R %f in (*.txt) do (
set filename=%~nxf
set new= =
ren ""
)
That can be seen on debugging the batch file by running it from within a command prompt window instead of double clicking the batch file. This results in the following error message for each *.txt file found in current directory and all its subdirectories:
The syntax of the command is incorrect.
The syntax of the command ren is of course incorrect.
One solution is using following batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "delims=" %%I in ('dir "* *.txt" /A-D /B /S 2^>nul') do (
set "FullName=%%I"
set "FileName=%%~nxI"
setlocal EnableDelayedExpansion
ren "!FullName!" "!FileName: =!"
endlocal
)
endlocal
The first two lines define completely the required execution environment for the batch file.
There is not used a for /R loop as that can cause troubles depending on file system of current drive and the file names to modify on renaming the files with file extension .txt while the FOR loop iterates of the file system entries matching the wildcard pattern.
The usage of the for /F loop results in first starting one more command process in background with %ComSpec% /c and the specified command line appended as additional arguments. So with Windows installed in C:\Windows is executed in background:
C:\Windows\System32\cmd.exe /C dir "* *.txt" /A-D /B /S 2>nul
The second command process runs DIR which
searches in current directory and all its subdirectories because of option /S
for just files because of option /A-D (attribute not directory)
of which name matches the wildcard pattern * *.txt in long or short name
and outputs the found file names in bare format because of option /B which means just the file names with full path because of option /S.
The command DIR finds also matching file names of files with hidden attribute set which are ignored by for /R. The option /A-D could be modified to /A-D-H to ignore hidden files.
The wildcard pattern contains a space character. For that reason the command DIR outputs just the full qualified file names of files which contain at least one space character in long file name. Short 8.3 file names cannot contain a space character.
The error message output by DIR if it cannot find at least one file name matching the wildcard pattern in the entire directory tree of current directory is suppressed by redirecting the error message from handle STDERR to device NUL.
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 command FOR respectively the cmd.exe instance processing the batch file captures all lines output by DIR to handle STDOUT of command process started in background. The processing of the list of full qualified file names starts when started cmd.exe closed itself after finishing execution of command DIR.
The list of file names to process is now completely in memory of the command process executing the batch file. The file renames done next by the loop cause multiply changes in file system, but that does not affect the list of file names processed by FOR as it is the case on using for /R. So there is surely no file name with a space in name skipped as the file system changes do not affect the processing of the files to rename.
FOR with option /F results by default in ignoring all empty lines. The command DIR does not output empty lines.
Next a non-empty line is split up by default into substrings using horizontal tab and normal space as string delimiters. That string splitting behavior is definitely not wanted here as the files to rename contain at least one space character. For that reason delims= is used to define an empty list of string delimiters which turns off the line splitting behavior completely.
There is by default ignored next a line of which first substring starts with default end of line character ;. But the command DIR with option /S outputs all file names with full path and it is therefore impossible that any full qualified file name starts with a semicolon. So it is not necessary to modify the default end of line character.
The full file name is assigned to loop variable I which is next assigned to the environment variable FullName. The file name with file extension without path is assigned to environment variable FileName. The environment variables are (re)defined while delayed environment variable expansion is disabled to process also file names correct containing one or more ! in name. If delayed expansion would be already enabled, each exclamation mark in file name assigned to loop variable I would be interpreted as beginning/end of a delayed expanded environment variable reference which of course is not wanted in this case.
Now delayed expansion is enabled to be able to rename the file using its full file name referenced delayed expanded and its new name without path with all spaces removed. Then the previous environment is restored which is necessary to avoid a stack overflow as there is much more done in background by setlocal EnableDelayedExpansion than toggling the state of delayed expansion and to process the next file name again in an environment with delayed expansion disabled. See this answer for details on what happens in background on each usage of the commands SETLOCAL and ENDLOCAL.
There is no guarantee that each file rename really works. The file rename fails if there is already a file or directory with new name in the directory of a file to rename. A file rename fails also if a file to rename is currently opened by an application which opened it with denying any access by another application.
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 /?
echo /?
endlocal /?
for /?
ren /?
set /?
setlocal /?

Iterate folder and get filename for commandline input

I am trying to iterate files in a folder and process them with another batch file inside the do loop. It works with echo but as soon as I use the variable as input to the program, it echoes the () part and everything inside.
Here's what I'm trying to do.
#echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
for /r %%f in (/folder/*) do (
set name="%%~nf"
echo !name! <--- ok
process.bat !name! <--- echoes () and commands inside this do loop
)
ENDLOCAL
The process.bat just capitalizes the first letter of the filename and echoes it for debug or confirmation.
A batch file must be called from within a batch file using command call as otherwise Windows command processor continues processing on other batch file with never returning back to initial batch file.
See also: How to call a batch file that is one level up from the current directory?
Please read excellent answer on batch file echo on/off not working properly written by dbenham for the reason on getting suddenly the commands executed by FOR output after first execution of process.bat without using command CALL. I cannot explain better what happens in this case.
The directory separator on Windows is the backslash character \ and not the forward slash / as on Linux or Mac. Windows supports also / in file/folder paths for compatibility reasons by automatically replacing all / by \ before accessing the Windows file systems, but a good written script uses 100% correct syntax and does not depend on automatic corrections done by other programs. / is used on Windows mainly for command line switches.
The usage of / instead of \ can result in an unexpected behavior. For example run a batch file with following content:
#echo off
echo Files in directory %SystemRoot:\=/%/:
for %%I in (%SystemRoot:\=/%/*) echo %%I
echo/
pause
echo/
echo Files in directory %SystemRoot%\:
for %%I in (%SystemRoot%\*) echo %%I
echo/
pause
The first FOR using C:/Windows/* as wildcard pattern outputs the file names with just drive letter + colon + file name + file extension. The file path \Windows\ is missing in output file names. The second FOR loop using C:\Windows\* as wildcard pattern outputs the full qualified file names, i.e. drive letter + colon + file path + file name + file extension.
A file/folder path starting with \ references a directory or file relative to root directory of current DRIVE.
This is explained by the Microsoft documentation Naming Files, Paths, and Namespaces.
It looks like folder is a subdirectory in directory of the executed batch file. In this case / or \ at beginning of folder path is definitely not correct. The backslash at beginning can be omitted or .\ is used to reference the directory folder in current directory on execution of the batch file. But the current directory on batch file execution can be also different to directory containing the executed batch file, for example on running the batch file as administrator, or on running the batch file as scheduled task, or on running the batch file from a network resource accessed using a UNC path. For that reason it is advisable to reference explicitly subdirectory folder in directory of the batch file.
Delayed environment variable expansion is not needed as long as the file name assigned currently to the loop variable does not need to be modified other than the modifiers of for support it. A command line like set name="%%~nf" does not work correct with enabled delayed expansion and file name contains one or more ! because of cmd.exe interprets the exclamation mark(s) in file name as beginning/end of a delayed expanded environment variable reference.
See also: How does the Windows Command Interpreter (CMD.EXE) parse scripts?
It looks like a recursive search for non-hidden files is not really needed as otherwise passing just file name without path and file extension would be not enough to get the right file processed by other batch file process.bat.
So the entire task can be done most likely also with:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%I in ("%~dp0folder\*") do call "%~dp0process.bat" "%%~nI"
endlocal
But if the other batch file process.bat expects that the passed file name without file extension and path is in current directory on execution of process.bat, it is necessary to make the subdirectory folder in directory of this batch file first the current directory.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0folder"
for %%I in (*) do call "%~dp0process.bat" "%%~nI"
popd
endlocal
Note: The batch file folder path referenced with %~dp0 always ends with a backslash. Therefore no additional backslash should be used on concatenating this path string with a file/folder name to avoid having finally on execution of the batch file \\ in full qualified file/folder name, although Windows kernel corrects such paths also automatically by removing second backslash in this case.
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 /?
endlocal /?
popd /?
pushd /?
set /?
setlocal /?

Command to run a .bat file

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

Copy file to user folder with a command line

I have search the web high and low, but can not find away to copy a file to the desktop with a command line.
Xcopy File.exe c:/users/%username%/desktop
This gives me a error like
Access denied
I look in to robocopy also, with no luck.
Is there another program i can use?
Ps. I also tested
takeown /f <foldername> /r /d y
We use backslashes for paths. Forward slash is switch and backslash is path separator.
Use %userprofile%\desktop. If the path is likely to have spaces enclose in quotes.
copy c:\windows\win.ini "%userprofile%\desktop\*.*"
Reference
& 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
| 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 concatinate 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.
%<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 seperates 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.
< > : " / \ | 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
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
.
--

Resources