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%
Related
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.
Task
I'm trying to make a launcher (in batch) for my (almost) all batch program in the Program Files (x86) folder. I also need it to be compatible with any one's Windows 10 machine.
Problem
The cd command does not evaluate the path correctly. It just says The directory name is invalid.
Code
#echo off
color 02
cls
cd "%~dp0batchfile.bat"
start /max /realtime %cd%
exit
Debug
I've moved the file around, adjusted the code, and even put the raw path and it all worked! But it still gives the error and causes the program to malfunction. I'm worried it can cause damage to someone's computer and to others' as well. (It's pretty overcomplicated for batch lol) I've also tried to echo the cd before, the path it's supposed to be set to, and the cd after. The cd before and what it's to be set to is fine, but it still says The directory name is invalid. And "doesn't" get set. Here is the code I tried:
#echo off
color 02
cls
cd "%~dp0batchfile.bat"
rem Debug:
echo %cd%
pause
rem real code:
start /max /realtime %cd%
exit
And it's fine. It gives the error, yet it works without interruption and causes less lag and glitches. I haven't a clue why because for my smol phatt brain this shouldn't even be possible. Bless you. Maybe it's just a bug that Microsoft needs to fix, but whatever it is, it is so annoying and it ruins the cleanliness of my (almost) all batch program.
Conclusion (That you made)
You think: This imbecile doesn't even know where to START when asking questions on StackOverflow.
Me reading your thoughts: This is the first question I ask on StackOverflow. So yes, I mean no, no yes, wait wait no, I don't know where to start. What? Bless you. Oop Bless you again.
cd "%~dp0batchfile.bat"
Why are you trying to cd into a batch file in the same directory as your script? That's obviously not going to work, as per the transcript you'll see idf you let cmd echo the commands before executing them (by commenting out the echo off, along with other stuff not needed for debugging):
rem #echo off
rem color 2
rem cls
cd "%~dp0batchfile.bat"
rem start /max /realtime %cd%
rem exit
If you run that, you'll see:
C:\Users\Allan>rem #echo off
C:\Users\Allan>rem color 02
C:\Users\Allan>rem cls
C:\Users\Allan>cd "C:\Users\Allan\batchfile.bat"
The system cannot find the path specified.
C:\Users\Allan>rem start /max /realtime C:\Users\Allan
C:\Users\Allan>rem exit
In other words, you probably should just be using %~dp0 in the cd command.
batchfile.bat is a FILE and not a directory. So it is not possible to change current directory to file batchfile.bat.
One solution is cd /D "%~dp0" to change the current directory to directory containing the currently executed batch file. This works as long as the batch file is stored on a storage media with a drive letter assigned. So the code would be:
#echo off
cd /D "%~dp0"
color 02
cls
start "Window Title" /MAX "FileName.exe"
color
But a batch file could be stored also on a network resource started with using UNC path. Windows command processor cmd.exe does not allow by default that a network resource path is set as current directory. The following code would be necessary for such use cases.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || goto :EOF
color 02
cls
start "Window Title" /MAX "FileName.exe"
color
popd
But a launcher batch file should not make the directory of itself the current directory, but the directory of the batch file to launch of which file name is passed to the launcher batch file as first argument. So a launcher batch file for other batch files could be:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if "%~1" == "" (
color 02
cls
echo INFO: "%~nx0" must be started with a batch file name.
echo/
pause
color
) else start "%~n1" /MAX %SystemRoot%\System32\cmd.exe /C "pushd "%~dp1" && (color 02 & cls & "%~nx1" & popd)"
endlocal
Do not use command exit to exit cmd.exe independent on calling hierarchy. That is not necessary here and makes it only more difficult to debug the batch file on executing it from within a command prompt window.
Do not use option /REALTIME of command START because this process priority class is mainly for drivers and should never be used for other executables and definitely not for a batch file processed by cmd.exe.
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 /? explaining:
%~dp0 ... drive and path of argument 0, the full batch file path always ending with a backslash,
%~1 ... first argument with surrounding double quotes removed,
%~n1 ... file name of first argument,
%~dp1 ... drive and path of first argument,
%~nx1 ... file name and extension of first argument.
cd /?
cls /?
cmd /?
color /?
echo /?
endlocal /?
goto /?
if /?
pause /?
popd /?
pushd /?
setlocal /?
start /?
See also single line with multiple commands using Windows batch file.
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 /?
cd %cd%
ffmpeg -i %cd%/%04d.png out.mp4
A script with just this in it works completely fine and outputs exactly what I need it to, but:
:: A simple script to convert a png or jpg image sequence to an
mp4 file with ffmpeg
cls
#echo off
title PNG2MP4
color C
echo Ensure you have ffmpeg installed and setup in your environment variables or this script won't work.
:QUERY
echo This will convert all image files in the following directory to a single mp4,
echo %cd%
echo are the files PNGs or JPEGs(PNG/P/JPG/J/CANCEL)?
set/p "ch=>"
if /I %ch%==PNG goto CONVERTPNG
if /I %ch%==P goto CONVERTPNG
if /I %ch%==JPG goto CONVERTJPG
if /I %ch%==J goto CONVERTJPG
if /I %ch%==CANCEL goto :eof
echo Invalid choice & goto QUERY
:CONVERTPNG
cd %cd%
ffmpeg -i %cd%/%04d.png out.mp4
:CONVERTJPG
cd %cd%
ffmpeg -i %cd%/%04d.jpg out.mp4
This more complex version of the script fails, outputting:
C:\tmp/img2mp4.bat4d.jpg: No such file or directory
Why is it no longer calling the files that it did before and is there an easy fix for this?
Here is my suggestion for the batch file:
#echo off
rem A simple script to convert a png or jpg image sequence to an mp4 file with ffmpeg
cls
title PNG2MP4
color C
echo Ensure you have ffmpeg installed and setup in your environment variables
echo or this script won't work.
echo/
echo This will convert all image files in the following directory to a single mp4:
echo/
echo %cd%
echo/
%SystemRoot%\System32\choice.exe /C PJC /N /M "Are the files PNGs or JPEGs or Cancel (P/J/C)? "
if errorlevel 3 color & goto :EOF
echo/
if errorlevel 2 (
ffmpeg.exe -i %%04d.jpg out.mp4
) else (
ffmpeg.exe -i %%04d.png out.mp4
)
color
The character % must be escaped in a batch file with one more % to be interpreted as literal character which was the main problem causing the batch file not working as expected. %0 references the string used to start the batch file which was img2mp4.bat. So %04d.jpg concatenated img2mp4.bat with 4d.jpg and the result was running ffmpeg.exe with img2mp4.bat4d.jpg as file name instead of the argument string %04d.jpg.
To reference one or more files/folders in current directory the file/folders can be simply specified in arguments list of a script or application with no path. This is explained in Microsoft documentation about Naming Files, Paths, and Namespaces. This page describes further that on Windows the directory separator is the backslash character \ and not the forward slash / as on Linux and Mac. / is used on Windows mainly for options as it can be seen on line with command CHOICE because of this character is not possible in file/folder names. - is used on Linux/Mac for options which is possible also in file/folder names even as first character of a file/folder name. So on Windows \ should be always used as directory separator although the Windows kernel functions for file system accesses automatically correct / in file/folder names to \.
CHOICE is much better for prompting a user to take a choice from several offered options than the command SET with option /P. set/p is syntactically not correct at all because of command set should be separated with a space from option /P which should be separated with a space from next argument variable=prompt text. set/p forces cmd.exe to automatically correct the command line to set /p. Batch files should be syntactically correct coded and not depend on automatic error corrections of Windows command processor.
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 how to reference batch file arguments.
echo /?
rem /?
cls /?
title /?
color /?
set /?
choice /?
if /?
goto /?
Further I suggest to read:
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
Single line with multiple commands using Windows batch file
ECHO. FAILS to give text or blank line - Instead use ECHO/
Where does GOTO :EOF return to?
I am having a problem on running a script to create empty files in a loop.
This is what have done so far:
#echo off
for /l %%a (1;1;20) do (echo m> ".mp4" c:\test)
pause
exit
Basically I have twenty names in a file on my desktop and I intend to create them as empty *.mp4 files in folder c:\test with the command echo m> .mp4. When I run the code above, it does not seem to work.
The following FOR loop can be used in the batch file to create empty files 1.mp4, 2.mp4, 3.mp4, ..., 20.mp4 in directory C:\test as suggested by rojo:
for /L %%I in (1,1,20) do type NUL >"C:\test\%%I.mp4"
And the next FOR loop can be used in the batch file to read the file names for the empty *.mp4 files to create from a list file on Windows desktop of current user as also suggested by rojo:
for /F "usebackq delims=" %%I in ("%USERPROFILE%\Desktop\List of Names.txt") do type NUL >"C:\test\%%I.mp4"
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.
for /?
type /?
Further the Microsoft article Using command redirection operators should be read explaining the redirection operator > and the SS64 page about NUL (null device).