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 /?
Related
I'm getting wrong with the older version Microsoft Edge and now I can't open pdf files with it. Though the newer version is available, I don't really like the newer version.Yesterday I learned that I can use Microsoft Edge to open pdf file through command line like below, but I don't know how to dynamically attach the filepath of the pdf to my batch script when I choose to open the pdf with my batch script.
start shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge file:\\\d:\\xxx.pdf
Open a command prompt, run call /? and read the output help carefully and completely. It explains how batch file arguments can be referenced from within a batch file. Argument 0 is always the batch file itself.
The batch file for your purpose could be coded as:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=%~1"
if not defined FileName goto PrintHelp
set "FileName=%FileName:"=%"
if not defined FileName goto PrintHelp
if "%FileName%" == "/?" goto PrintHelp
set "FileName=%FileName:/=\%"
if not exist "%FileName%" (
echo ERROR: File not found: "%FileName%"
echo/
pause
goto EndBatch
)
set "FileName=%FileName:\=/%"
if not "%FileName:~0,1%" == "/" set "FileName=///%FileName%"
start "" shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge "file:%FileName%"
goto EndBatch
:PrintHelp
echo INFO: %~nx0 must be called with name of a file to open in Microsoft Edge.
echo/
pause
:EndBatch
endlocal
I do not really understand why a batch file is needed at all to open PDF files in Microsoft Edge. It would be also possible to simply associate the file extension .pdf with Microsoft Edge to get PDF files opened by default with Microsoft Edge.
The following command line can be executed in a command prompt window to get displayed which application is associated currently with file extension .pdf and which command is used to open a PDF file with %1 being the placeholder for the file name:
for /F "skip=1 tokens=2*" %I in ('%SystemRoot%\System32\reg.exe query HKEY_CLASSES_ROOT\.pdf /ve 2^>nul') do %SystemRoot%\System32\reg.exe query "HKEY_CLASSES_ROOT\%J\Shell\Open\Command" /ve
For understanding the commands used in the batch file and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
goto /?
if /?
pause /?
set /?
setlocal /?
start /?
See also the Wikipedia article about file URI scheme. It would be necessary to percent encode the file name for a 100% correct file URL, but Microsoft Edge supports also not correct encoded file URLs containing for example a space character instead of %20 or the umlaut ä instead of %c3%a4.
I'd assume that you could open your pdf located in the same directory as your batch-file, with the assistance of powershell:
#Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
Set "filename=myfile! - 100%% virus free.pdf"
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -Command "[System.Diagnostics.Process]::Start(\"msedge\",\"`\"%~dp0%filename%`\"\")"
You would replace my example filename with your own on line 2, (taking special care not to touch the closing doublequote). Please note that I have deliberately used a filename of myfile! - 100%% virus free.pdf, to show you that you must double any percent character in your filename, (as the percent character requires special treatment when used in a batch file).
In fact I got my answer after viewing some dos doc. And below is my solution(which is available for open pdf with 'open with' this batch script. To avoid opening the cmd window(it's ugly to my view), I also convert it to a exe using bat2exe converter.
#echo off
set prefix=file:///
set filepath=%~f1
set truepath=%filepath%%filepath:\=/%
start shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge %truepath%
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.
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 /?
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 /?
I have been wanting my script to find a folder that starts with the string "onedrive...".
My code looks like this,
#echo off
set path="C:\Users\%USERNAME%"
if exist %path% (
cd "%path%\onedrive*"
echo %cd%
cd
)
pause
and the output I get is,
C:\Users\310176421\Backupscript\source
C:\Users\310176421\OneDrive for Business
where the first one is my .bat file directory and the second one is the line i want to make into a variable.
Any ideas?
Oh man don't do this, you are overwriting the system PATH. You have to use another name for that variable. And also you have to set it as local.
#echo off
SETLOCAL
REM blah blah
set _my_custom_path=....
ENDLOCAL
Here is a simple batch code which searches in profile directory of current user for a directory starting with string OneDrive and assigns the full path of first found folder without quotes to an environment variable output next before exiting batch.
#echo off
for /F "delims=" %%I in ('dir /AD /B /S "%USERPROFILE%\OneDrive*" 2^>nul') do (
set "OneDriveFolder=%%~I"
goto FoundFolder
)
echo Could not find a folder OneDrive.
goto :EOF
:FoundFolder
echo Found folder: %OneDriveFolder%
set "OneDriveFolder="
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
for /?
goto /?
set /?
Note 1: C:\Users\%USERNAME% is not always equal %USERPROFILE% as the profile directory can be also on another drive than drive C: and Users is just the default parent directory for the user profiles on Windows Vista and later.
Note 2: 2^>nul redirects error message output by command DIR to stdout to device nul which means suppressing the error message in case of no directory starting with OneDrive is found case-insensitive. ^ escapes redirection operator > for command FOR to get 2>nul applied on command DIR.