open folder by input in batch and C++ code - batch-file

I searched how to open the folder in batch code as following
%SystemRoot%\explorer.exe "c:\Yaya\yoyo\"
However, what if I want to give the specific folder everytime i execute the batch program?
If you don't mind, could you also please tell me how to do it in C++ as well?
It is hard to change the path by having scanf..
Currently I have
#include <windows.h>
#include <iostream>
int main ()
{
HINSTANCE result;
result=ShellExecute(NULL,NULL,L"c:\my_folder_path_by_input",NULL,NULL,SW_SHOWDEFAULT);
if ((int)result<=32)
std::cout << "Error!\nReturn value: " << (int)result << "\n";
return 0;
}

Run the batch file with path of folder to open as parameter and use in batch file %SystemRoot%\explorer.exe "%~1" or perhaps even better %SystemRoot%\explorer.exe /e,"%~1".
Example:
Batch file OpenFolder.bat contains:
#echo off
if "%~1" == "" (
%SystemRoot%\explorer.exe
) else (
%SystemRoot%\explorer.exe /e,"%~1"
)
This batch file is started for example with one of the lines below:
OpenFolder.bat
OpenFolder.bat %windir%\Temp
OpenFolder.bat "%TEMP%"
OpenFolder.bat "%APPDATA%"
OpenFolder.bat "%USERPROFILE%\Desktop"
Enclosing the folder path in double quotes is always possible, but really required are the double quotes on running OpenFolder if the folder path contains anywhere a space character or one of these characters: &()[]{}^=;!'+,`~
See also Windows Explorer Command-Line Options
I'm not sure why a batch file is needed at all to open a specific folder in Windows Explorer. Pressing Windows+E opens in any Windows starting from Windows 95 a new Windows Explorer window. And entering in address bar of Explorer window one of the strings above results in displaying the appropriate folder. See also Microsoft page about Windows Keyboard Shortcuts.
Here is one more batch version asking user for a folder path if not specified as parameter on starting the batch file.
#echo off
if not "%~1" == "" (
%SystemRoot%\explorer.exe /e,"%~1"
goto :EOF
)
rem There is no folder path specified as parameter.
rem Prompt user for folder path and predefine the environment variable
rem with a double quote as value to avoid batch processing exit because of
rem a syntax error if the batch file user just hits key RETURN or ENTER.
set "FolderPath=""
set /P "FolderPath=Folder path: "
rem Remove all double quotes from string entered by the user.
set "FolderPath=%FolderPath:"=%"
if "%FolderPath%" == "" (
%SystemRoot%\explorer.exe
) else (
%SystemRoot%\explorer.exe /e,"%FolderPath%"
set "FolderPath="
)
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 %~1 (first parameter without double quotes).
echo /?
goto /?
if /?
rem /?
set /?

Related

How can I find my error in the batch script?

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.

How can I copy and rename a file using an environment variable?

I'm working with the command prompt for nearly the first time and am required to create a batch file that prompts the user for a filename with an extension. The bat is supposed to be able to copy and rename said file. The instructor has directed us to use environmental variables to accomplish this task, but I keep getting directory or syntax errors.
I've tried using the variable that the user sets with a previous prompt, but unfortunately this particular instructor hasn't given us practical examples about how to accomplish this particular goal, so I'm flailing. I've tried attaching the variable to the target directory with a generic name for the file. The file and the copy should be in the dame directory.
set /P file_var=Please enter a file name and extension:
copy %file_var% Templatecopy.doc
The file should be copied with the new default name of "Templatecopy.doc" in the target directory.
Churns out syntax and directory errors.
I suggest the following commented code to make this batch file fail-safe as described in answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
#echo off
:FileNamePrompt
rem Undefine environment variable FileToCopy.
set "FileToCopy="
rem Prompt user for the file name.
set /P "FileToCopy=Please enter a file name and extension: "
rem Has the user not entered anything, prompt the user once more.
if not defined FileToCopy goto FileNamePrompt
rem Remove all double quotes from user input string.
set "FileToCopy=%FileToCopy:"=%"
rem Has the user input just one or more ", prompt the user once more.
if not defined FileToCopy goto FileNamePrompt
rem Check if the user input string really references an existing file.
if not exist "%FileToCopy%" (
echo File "%FileToCopy%" does not exist.
goto FileNamePrompt
)
rem Check if the user input string really references
rem an existing file and not an existing directory.
if exist "%FileToCopy%\" (
echo "%FileToCopy%" references a directory.
goto FileNamePrompt
)
copy /B /Y "%FileToCopy%" "%~dp0Templatecopy.doc" >nul
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 which is expanding to drive and path of argument 0 which is the batch file path always ending with a backslash.
copy /?
echo /?
goto /?
if /?
rem /?
set /?

having trouble using spaces in folder names

When the user enters a space in the folder name, I can create and remove the folder with the following code, but the line to start or open the folder will not work.
I have tried several different things. If I use the "%input%" in the start line the quotes are used as part of the folder name so it is not recognized. If I eliminate the ""'s only the first word in the name is recognized so the folder is not found. the Md and Rd lines work perfectly with the quotes.
#echo off
echo Type in the name of your folder and hit enter.
set /P x=Please type the folder name here:
md %userprofile%\desktop\"%x%"
start %userprofile%\desktop\"%x%"
pause
rd %userprofile%\desktop\"%x%"
I expected the folder to open on the desktop and just get an error that the name is not recognized.
Please read answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input? and the commends in batch code below for understanding why this code is much better for your task.
It is usually necessary to enclose the entire argument string in double quotes and not just parts of it as it can be seen below.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
echo Type in the name of your folder and hit ENTER.
:UserPrompt
set "Folder="
set /P "Folder=Please type the folder name here: "
rem Has the user entered a string at all?
if not defined Folder goto UserPrompt
rem Remove all double quotes of user input string.
set "Folder=%Folder:"=%"
rem Was not only one or more double quotes entered by the user?
if not defined Folder goto UserPrompt
rem Create the folder with suppressing the error message.
md "%UserProfile%\Desktop\%Folder%" 2>nul
rem Could the folder name be created at all which means the user
rem input string was valid and the folder did not exist already?
if errorlevel 1 goto UserPrompt
rem Open the just created folder on user's desktop.
start "" "%UserProfile%\Desktop\%Folder%"
pause
rd "%UserProfile%\Desktop\%Folder%"
endlocal
Instead of the command line
start "" "%UserProfile%\Desktop\%Folder%"
it is also possible to use
%SystemRoot%\explorer.exe "%UserProfile%\Desktop\%Folder%"
or use
%SystemRoot%\explorer.exe /e,"%UserProfile%\Desktop\%Folder%"
explorer.exe is an exception of general rule to enclose an entire argument string in double quotes. "/e,%UserProfile%\Desktop\%Folder%" would not work because in this case the argument string would be interpreted as folder with an invalid relative path to root directory of current drive instead of option /e with folder to open.
But Windows Explorer does not offer options to define window position and size. Whatever the user used the last time and is therefore most likely preferred by the user is used again by Windows Explorer on opening an Explorer window for a folder.
It would be of course possible with additional code to send to the just opened Explorer window being top-level foreground window a message for changing window position and size. See for example:
How can a batch file run a program and set the position and size of the window?
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 /?
endlocal /?
if /?
md /?
pause /?
rd /?
rem /?
set /?
setlocal /?
start /?

7z "Incorrect command line" when I run the script in a different drive than C:

I'm doing a batch script so I can compress multiple directories inside a specific folder.
The thing is it works perfectly if the folder is at C:\something, but if I try to do the same to a folder in i.e E:\something, I get an error.
The script is this:
#ECHO OFF
if %1.==. (
SET "rootpath=%cd%"
) else (
SET "rootpath=%~1"
)
FOR /D %%D IN ("%rootpath%\*") DO (
7za a -t7z %%D.7z %%D\* -mx9
)
Example of how it works normally:
C:\Users\Me\Desktop\ExampleFolder>script
7-Zip (A) 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Scanning
Creating archive C:\Users\Me\Desktop\ExampleFolder\D1.7z
Everything is Ok
7-Zip (A) 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Scanning
Creating archive C:\Users\Me\Desktop\ExampleFolder\D2.7z
Everything is Ok
Example of how it fails:
C:\Users\Me\ExampleFolder>script "E:\Documents\ExampleFolder"
Error:
Incorrect command line
Error:
Incorrect command line
Of course, I also tried to execute the script in the same folder and I checked that it works when I pass the location as an argument. Thanks.
There are 2 mistakes in the batch code.
The first one is not making sure that path assigned to rootpath does not end with a backslash resulting in %%D containing a path with two successive backslashes.
Two successive backslashes in path caused by this coding omission mistake depends on parameter string on calling the batch or when the batch file is executed from root of a drive because in this case %cd% expands to a path consisting of drive letter, a colon and a backslash. %cd% expands to a path without a backslash at end if current directory is not root directory of a drive. However, this mistake is not critical.
The second one is the real problem on using a directory path containing a critical character like a space or one of these characters: &()[]{}^=;!'+,`~
%%D.7z and %%D\* are not enclosed in double quotes making the parameters list for 7za.exe invalid especially with 1 or more spaces in path.
How I found that out?
I inserted command echo left of 7za to see what would be executed in the loop. I don't have 7-Zip installed and therefore needed the echo to test the batch file.
The solution:
#echo off
if "%~1" == "" (
set "RootPath=%CD%"
) else (
set "RootPath=%~1"
)
if "%RootPath:~-1%" == "\" set "RootPath=%RootPath:~0,-1%"
for /D %%D in ("%RootPath%\*") do (
7za.exe a -t7z "%%D.7z" "%%D\*" -mx9
)
If this batch file is executed on always the same computer where path to 7za.exe is known, it would be good to specify 7za.exe with full path enclosed in double quotes in the batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cmd /? ... read at least the last paragraph on last output help page.
echo /?
for /?
if /?
set /?
Give a try for this batch file :
#echo off
set rootpath=c:\test
set strProgramFiles=%ProgramFiles%
if exist "%ProgramFiles(x86)%" set strProgramFiles=%ProgramFiles(x86)%
Set Path7z="%strProgramFiles%\7-zip\7z.exe"
echo %Path7z%
pause
CD /D "%rootpath%"
FOR /D %%D IN ("%rootpath%\*") DO (
%Path7z% a -t7z %%D.7z %%D\* -mx9
)
pause

Check and make list of jpg files if present to a text file using batch script

I have a project which has following steps:
Create list of jpg files in a folder (initially there is none).
Go to step 1 if the created text file is empty.
Start another program (this program needs the received jpg file as input) if the created list file in step 1 is not empty.
JPG file will be sent to this folder by another process.
I am new to using batch script and used the following code from input.
But this program is not starting another process as required in step 3 even after receiving JPG file.
What is wrong with my code?
#echo off
set "dir=E:\test"
set "file=%dir%\a.txt"
:start
dir/b *.jpg>a.txt
if "%~z1" == "" (
goto start
)
if "%~z1" == "0" (
goto start
)
if "%~z1" == "1" (
Start "" "C:\Users\vamsidhar muthireddy\Documents\Visual Studio 2010\Projects\database_test0\Debug\database_test0.exe"
)
Don't name a variable like an internal command. It is possible to name a variable dir although there is also the command DIR, but it is not advisable.
Don't name a label like an internal command. It is possible to name a label start although there is also the command START, but it is not advisable.
Why is it not advisable to name a variable or label like a command?
Well, for example if in future somebody wants to find where variable dir is used and the batch file contains also command DIR, or wants to rename label start by running a replace and batch file contains also command START, these actions become difficult as it must be analyzed in which context dir and start are used on each found occurrence.
Also syntax highlighting of batch file code is definitely not correct with commands DIR and START as the variable dir and the label start would be most likely also highlighted as commands.
The main coding mistake is %~z1 as this is replaced by file size of the file specified with its file name as first argument on calling the batch file if the batch file was called at all with a file name of an existing file. But this is not the case here. The intention here was getting size of the list file. Also if "%~z1" == "1" will be nearly never true. This condition becomes only true if the file specified as parameter has a file size of exactly 1 byte.
Here is a commented batch code which I think is more useful for the task:
#echo off
set "SourceDirectory=E:\test"
rem This loop is executed with a delay of 5 seconds between each loop run
rem until at least 1 file with extension JPG is found in the defined source
rem directory. Then the JPG file is processed and batch processing ends.
:Loop
echo Checking for a *.jpg file in %SourceDirectory% ...
if exist "%SourceDirectory%\*.jpg" goto ProcessFile
%SystemRoot%\System32\ping.exe 127.0.0.1 -n 6 >nul
goto Loop
:ProcessFile
for %%I in ("%SourceDirectory%\*.jpg") do (
echo Processing %%I ...
start "" "%USERPROFILE%\Documents\Visual Studio 2010\Projects\database_test0\Debug\database_test0.exe" "%%I"
)
rem Delete the created variable before exiting batch processing.
set "SourceDirectory="
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 /?
goto /?
if /?
ping /?
rem /?
set /?
start /?

Resources