Recently installed Anaconda (1.9) for my python project on win7
After installation, I built a python 3 support environment with instruction in this page. My next task is to activate my python environment automatically with built-in batch file.
I used the command in [Anaconda Command Prompt] shortcut I found in my start menu. It runs a batch-file called [anaconda.bat]
After observing the batch file I realized it seems to be capable of taking an input argument that is supposed to be the environment I would like to activate. So I copied the shortcut and modified it as
C:\Windows\System32\cmd.exe /k "C:\Anaconda\Scripts\anaconda.bat py3k"
Then I double clicked on the new shortcut, it opened a new command window but...the designated environment did not activate!
#echo off
rem +===========================================================================
rem | Initialisation
rem +===========================================================================
verify bogus-argument 2>nul
setlocal enableextensions enabledelayedexpansion
if ERRORLEVEL 1 (
echo error: unable to enable command extensions
goto :eof
)
for %%i in ("%~dp0..\envs") do (
set ANACONDA_ENVS=%%~fi
)
if not "%1" == "" (
if not exist "%ANACONDA_ENVS%\%1\python.exe" (
echo No environment named "%1" exists in %ANACONDA_ENVS%
goto :eof
)
set ANACONDA_ENV_NAME=%1
set ANACONDA=%ANACONDA_ENVS%\%1
title Anaconda (%ANACONDA_ENV_NAME%^)
) else (
set ANACONDA_ENV_NAME=
for %%i in ("%~dp0..") do (
set ANACONDA=%%~fi
)
title Anaconda
)
set ANACONDA_SCRIPTS=%ANACONDA%\Scripts
for %%i in ("python.exe") do (
for %%j in ("%ANACONDA%\python.exe") do (
if not "%%~f$PATH:i" == "%%~f$PATH:j" (
set ANACONDA_OLD_PATH="%PATH%"
set PATH=%ANACONDA%;%ANACONDA_SCRIPTS%;%PATH%;
echo Added %ANACONDA% and %ANACONDA_SCRIPTS% to PATH.
)
)
)
if not "%ANACONDA_ENV_NAME%" == "" (
echo Activating environment %ANACONDA_ENV_NAME%...
set PROMPT=[%ANACONDA_ENV_NAME%] $P$G
)
I have very little experience with bat language but I guess there may be something to do with this line
setlocal enableextensions enabledelayedexpansion
I tried to remove that line but kept trapped in the ERRORLEVEL 1 expression with message.
error: unable to enable command extensions
Can anyone suggest what I should do to make this bat-file work properly?
I don't think you need a batch file. Assuming that Anaconda and CMD are on your path (which they should be), you can try this as an alternative (it is what I do):
cmd "/c activate py3k && ipython --pylab"
Related
I have a .bat I use to set some environment vars before running a few programs.
I'd like to permanently set these environment vars, but I don't want to do it manually if possible. Is there a shortcut here? Is there any flag I can set to permanently add to PATH ?
The code is from setupvars.bat made available with OpenVino :
set ROOT=%~dp0
call :GetFullPath "%ROOT%\.." ROOT
set SCRIPT_NAME=%~nx0
set "INTEL_OPENVINO_DIR=%ROOT%"
set "INTEL_CVSDK_DIR=%INTEL_OPENVINO_DIR%"
where /q libmmd.dll || echo Warning: libmmd.dll couldn't be found in %%PATH%%. Please check if the redistributable package for Intel(R) C++ Compiler is installed and the library path is added to the PATH environment variable. System reboot can be required to update the system environment.
:: OpenCV
if exist "%INTEL_OPENVINO_DIR%\opencv\setupvars.bat" (
call "%INTEL_OPENVINO_DIR%\opencv\setupvars.bat"
) else (
set "OpenCV_DIR=%INTEL_OPENVINO_DIR%\opencv\x64\vc14\lib"
set "PATH=%INTEL_OPENVINO_DIR%\opencv\x64\vc14\bin;%PATH%"
)
:: OpenVX
set "OPENVX_FOLDER=%INTEL_OPENVINO_DIR%\openvx"
set "PATH=%INTEL_OPENVINO_DIR%\openvx\bin;%PATH%"
:: Inference Engine
set "InferenceEngine_DIR=%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\share"
set "HDDL_INSTALL_DIR=%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\external\hddl"
set "PATH=%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\bin\intel64\Release;%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\bin\intel64\Debug;%HDDL_INSTALL_DIR%\bin;%PATH%"
if exist "%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\bin\intel64\arch_descriptions" (
set "ARCH_ROOT_DIR=%INTEL_OPENVINO_DIR%\deployment_tools\inference_engine\bin\intel64\arch_descriptions"
)
:: Check if Python is installed
python --version 2>NUL
if errorlevel 1 (
echo Error^: Python is not installed. Please install Python 3.5. or 3.6 ^(64-bit^) from https://www.python.org/downloads/
exit /B 1
)
:: Check Python version
for /F "tokens=* USEBACKQ" %%F IN (`python --version 2^>^&1`) DO (
set version=%%F
)
echo %var%
for /F "tokens=1,2,3 delims=. " %%a in ("%version%") do (
set Major=%%b
set Minor=%%c
)
if "%Major%" geq "3" (
if "%Minor%" geq "5" (
set python_ver=okay
)
if "%Minor%" geq "6" (
set python_ver=okay
)
)
if not "%python_ver%"=="okay" (
echo Unsupported Python version. Please install Python 3.5 or 3.6 ^(64-bit^) from https://www.python.org/downloads/
exit /B 1
)
:: Check Python bitness
python -c "import sys; print(64 if sys.maxsize > 2**32 else 32)" 2 > NUL
if errorlevel 1 (
echo Error^: Error during installed Python bitness detection
exit /B 1
)
for /F "tokens=* USEBACKQ" %%F IN (`python -c "import sys; print(64 if sys.maxsize > 2**32 else 32)" 2^>^&1`) DO (
set bitness=%%F
)
if not "%bitness%"=="64" (
echo Unsupported Python bitness. Please install Python 3.5 or 3.6 ^(64-bit^) from https://www.python.org/downloads/
exit /B 1
)
set PYTHONPATH=%INTEL_OPENVINO_DIR%\python\python%Major%.%Minor%;%PYTHONPATH%
echo PYTHONPATH=%PYTHONPATH%
echo [setupvars.bat] OpenVINO environment initialized
exit /B 0
:GetFullPath
SET %2=%~f1
GOTO :EOF
For OpenVINO, you need to run the setupvars.sh script every time you open a command line. However, you can also add all the variables needed to your systems environment variables.
On your Windows® 10 system, go to Control Panel > System and Security > System > Advanced System Settings > Environment Variables.
See this document for a list of required variables and their values.
I have a Windows batch file whose purpose is to set some environment variables, e.g.
=== MyFile.cmd ===
SET MyEnvVariable=MyValue
Users can run this prior to doing work that needs the environment variable, e.g.:
C:\> MyFile.cmd
C:\> echo "%MyEnvVariable%" <-- outputs "MyValue"
C:\> ... do work that needs the environment variable
This is roughly equivalent to the "Developer command prompt" shortcuts installed by Visual Studio, which set environment variables needed to run VS utilities.
However if a user happens to have a Powershell prompt open, the environment variable is of course not propagated back to Powershell:
PS C:\> MyFile.cmd
PS C:\> Write-Output "${env:MyEnvVariable}" # Outputs an empty string
This can be confusing for users who switch between CMD and PowerShell.
Is there a way I can detect in my batch file MyFile.cmd that it was called from PowerShell, so that I can, for example, display a warning to the user? This needs to be done without any 3rd party utility.
Your own answer is robust and while it is generally slow due to needing to run a PowerShell process, it can be made significantly faster by optimizing the PowerShell command used to determine the calling shell:
#echo off
setlocal
CALL :GETPARENT PARENT
IF /I "%PARENT%" == "powershell" GOTO :ISPOWERSHELL
IF /I "%PARENT%" == "pwsh" GOTO :ISPOWERSHELL
endlocal
echo Not running from Powershell
SET MyEnvVariable=MyValue
GOTO :EOF
:GETPARENT
SET "PSCMD=$ppid=$pid;while($i++ -lt 3 -and ($ppid=(Get-CimInstance Win32_Process -Filter ('ProcessID='+$ppid)).ParentProcessId)) {}; (Get-Process -EA Ignore -ID $ppid).Name"
for /f "tokens=*" %%i in ('powershell -noprofile -command "%PSCMD%"') do SET %1=%%i
GOTO :EOF
:ISPOWERSHELL
echo. >&2
echo ERROR: This batch file may not be run from a PowerShell prompt >&2
echo. >&2
exit /b 1
On my machine, this runs about 3 - 4 times faster (YMMV) - but still takes almost 1 second.
Note that I've added a check for process name pwsh as well, so as to make the solution work with PowerShell Core too.
Much faster alternative - though less robust:
The solution below relies on the following assumption, which is true in a default installation:
Only a system environment variable named PSModulePath is persistently defined in the registry (not also a user-specific one).
The solution relies on detecting the presence of a user-specific path in PSModulePath, which PowerShell automatically adds when it starts.
#echo off
echo %PSModulePath% | findstr %USERPROFILE% >NUL
IF %ERRORLEVEL% EQU 0 goto :ISPOWERSHELL
echo Not running from Powershell
SET MyEnvVariable=MyValue
GOTO :EOF
:ISPOWERSHELL
echo. >&2
echo ERROR: This batch file may not be run from a PowerShell prompt >&2
echo. >&2
exit /b 1
Alternative approach for launching a new cmd.exe console window on demand:
Building on the previous approach, the following variant simply re-invokes the batch file in a new cmd.exe window on detecting that it is being run from PowerShell.
This is not only more convenient for the user, it also mitigates the problem of the solutions above yielding false positives: When run from an interactive cmd.exe session that was launched from PowerShell, the above solutions will refuse to run, even though they should, as PetSerAl points out.
While the solution below also doesn't detect this case per se, it still opens a useable - albeit new - window with the environment variables set.
#echo off
REM # Unless already being reinvoked via cmd.exe, see if the batch
REM # file is being run from PowerShell.
IF NOT %1.==_isNew. echo %PSModulePath% | findstr %USERPROFILE% >NUL
REM # If so, RE-INVOKE this batch file in a NEW cmd.exe console WINDOW.
IF NOT %1.==_isNew. IF %ERRORLEVEL% EQU 0 start "With Environment" "%~f0" _isNew & goto :EOF
echo Running from cmd.exe, setting environment variables...
REM # Set environment variables.
SET MyEnvVariable=MyValue
REM # If the batch file had to be reinvoked because it was run from PowerShell,
REM # but you want the user to retain the PowerShell experience,
REM # restart PowerShell now, after definining the env. variables.
IF %1.==_isNew. powershell.exe
GOTO :EOF
After setting all environment variables, note how the last IF statement, also re-invokes PowerShell, but in the same new window, based on the assumption that the calling user prefers working in PowerShell.
The new PowerShell session will then see newly defined environment variables, though note that you'll need two successive exit calls to close the window.
As Joe Cocker used to say "I get by with a little help from my friends".
In this case from Lieven Keersmaekers, whose comments led me to the following solution:
#echo off
setlocal
CALL :GETPARENT PARENT
IF /I "%PARENT%" == "powershell.exe" GOTO :ISPOWERSHELL
endlocal
echo Not running from Powershell
SET MyEnvVariable=MyValue
GOTO :EOF
:GETPARENT
SET CMD=$processes = gwmi win32_process; $me = $processes ^| where {$_.ProcessId -eq $pid}; $parent = $processes ^| where {$_.ProcessId -eq $me.ParentProcessId} ; $grandParent = $processes ^| where {$_.ProcessId -eq $parent.ParentProcessId}; $greatGrandParent = $processes ^| where {$_.ProcessId -eq $grandParent.ParentProcessId}; Write-Output $greatGrandParent.Name
for /f "tokens=*" %%i in ('powershell -command "%CMD%"') do SET %1=%%i
GOTO :EOF
:ISPOWERSHELL
echo.
echo ERROR: This batch file may not be run from a PowerShell prompt
echo.
cmd /c "exit 1"
GOTO :EOF
I did something like this for Chocolatey's RefreshEnv.cmd script: Make refreshenv.bat error if powershell.exe is being used.
My solution didn't end being used, for unrelated reasons, but it's available in this repo: beatcracker/detect-batch-subshell. Here is copy of it, just in case.
Script that will only run if called directly from interactive command processor session
Script will detect if it's run from non-interactive session (cmd.exe /c detect-batch-subshell.cmd) and show approriate error message.
Non-interactive shell includes PowerShell/PowerShell ISE, Explorer, etc... Basically anything that will try to execute script by running it in the separate cmd.exe instance.
Hovewer, dropping into the cmd.exe session from PowerShell/PowerShell ISE and executing script there will work.
Dependencies
wmic.exe - comes with Windows XP Professional and up.
Example:
Open cmd.exe
Type detect-batch-subshell.cmd
Output:
> detect-batch-subshell.cmd
Running interactively in cmd.exe session.
Example:
Open powershell.exe
Type detect-batch-subshell.cmd
Output:
PS > detect-batch-subshell.cmd
detect-batch-subshell.cmd only works if run directly from cmd.exe!
Code
detect-batch-subshell.cmd
#echo off
setlocal EnableDelayedExpansion
:: Dequote path to command processor and this script path
set ScriptPath=%~0
set CmdPath=%COMSPEC:"=%
:: Get command processor filename and filename with extension
for %%c in (!CmdPath!) do (
set CmdExeName=%%~nxc
set CmdName=%%~nc
)
:: Get this process' PID
:: Adapted from: http://www.dostips.com/forum/viewtopic.php?p=22675#p22675
set "uid="
for /l %%i in (1 1 128) do (
set /a "bit=!random!&1"
set "uid=!uid!!bit!"
)
for /f "tokens=2 delims==" %%i in (
'wmic Process WHERE "Name='!CmdExeName!' AND CommandLine LIKE '%%!uid!%%'" GET ParentProcessID /value'
) do (
rem Get commandline of parent
for /f "tokens=1,2,*" %%j in (
'wmic Process WHERE "Handle='%%i'" GET CommandLine /value'
) do (
rem Strip extra CR's from wmic output
rem http://www.dostips.com/forum/viewtopic.php?t=4266
for /f "delims=" %%x in ("%%l") do (
rem Dequote path to batch file, if any (3rd argument)
set ParentScriptPath=%%x
set ParentScriptPath=!ParentScriptPath:"=!
)
rem Get parent process path
for /f "tokens=2 delims==" %%y in ("%%j") do (
rem Dequote parent path
set ParentPath=%%y
set ParentPath=!ParentPath:"=!
rem Handle different invocations: C:\Windows\system32\cmd.exe , cmd.exe , cmd
for %%p in (!CmdPath! !CmdExeName! !CmdName!) do (
if !ParentPath!==%%p set IsCmdParent=1
)
rem Check if we're running in cmd.exe with /c switch and this script path as argument
if !IsCmdParent!==1 if %%k==/c if "!ParentScriptPath!"=="%ScriptPath%" set IsExternal=1
)
)
)
if !IsExternal!==1 (
echo %~nx0 only works if run directly from !CmdExeName!^^!
exit 1
) else (
echo Running interactively in !CmdExeName! session.
)
endlocal
Like the answer from beatcracker I think it would be better to not take assumptions about the external shell that can be used to launch the batch script, for instance, the issue can also arise when running the batch file through the bash shell.
Because it exclusively uses the native facilities of CMD and has no dependency on any external tool or the WMI, the execution time is very fast.
#echo off
call :IsInvokedInternally && (
echo Script is launched from an interactive CMD shell or from another batch script.
) || (
echo Script is invoked by an external App. [PowerShell, BASH, Explorer, CMD /C, ...]
)
exit /b
:IsInvokedInternally
setlocal EnableDelayedExpansion
:: Getting substrings from the special variable CMDCMDLINE,
:: will modify the actual Command Line value of the CMD Process!
:: So it should be saved in to another variable before applying substring operations.
:: Removing consecutive double quotes eg. %systemRoot%\system32\cmd.exe /c ""script.bat""
set "SavedCmdLine=!cmdcmdline!"
set "SavedCmdLine=!SavedCmdLine:""="!"
set /a "DoLoop=1, IsExternal=0"
set "IsCommand="
for %%A in (!SavedCmdLine!) do if defined DoLoop (
if not defined IsCommand (
REM Searching for /C switch, everything after that, is CMD commands
if /i "%%A"=="/C" (
set "IsCommand=1"
) else if /i "%%A"=="/K" (
REM Invoking the script with /K switch creates an interactive CMD session
REM So it will be considered an internal invocatoin
set "DoLoop="
)
) else (
REM Only check the first command token to see if it references this script
set "DoLoop="
REM Turning delayed expansion off to prevent corruption of file paths
REM which may contain the Exclamation Point (!)
REM It is safe to do a SETLOCAL here because the we have disabled the Loop,
REM and the routine will be terminated afterwards.
setlocal DisableDelayedExpansion
if /i "%%~fA"=="%~f0" (
set "IsExternal=1"
) else if /i "%%~fA"=="%~dpn0" (
set "IsExternal=1"
)
)
)
:: A non-zero ErrorLevel means the script is not launched from within CMD.
exit /b %IsExternal%
It checks the command line that used to launch the CMD shell to tell if script have been launched from within CMD or by an external app using the command line signature /C script.bat which is typically used by non CMD shells to launch batch scripts.
If for any reason the external launch detection needs to bypasses, for instance when manually launching the script with additional commands to take advantage the defined variables, it can done by prepending # to the path of the script in CMD command line:
cmd /c #MyScript.bat & AdditionalCommands
Recently installed Anaconda (1.9) for my python project on win7
After installation, I built a python 3 support environment with instruction in this page. My next task is to activate my python environment automatically with built-in batch file.
I used the command in [Anaconda Command Prompt] shortcut I found in my start menu. It runs a batch-file called [anaconda.bat]
After observing the batch file I realized it seems to be capable of taking an input argument that is supposed to be the environment I would like to activate. So I copied the shortcut and modified it as
C:\Windows\System32\cmd.exe /k "C:\Anaconda\Scripts\anaconda.bat py3k"
Then I double clicked on the new shortcut, it opened a new command window but...the designated environment did not activate!
#echo off
rem +===========================================================================
rem | Initialisation
rem +===========================================================================
verify bogus-argument 2>nul
setlocal enableextensions enabledelayedexpansion
if ERRORLEVEL 1 (
echo error: unable to enable command extensions
goto :eof
)
for %%i in ("%~dp0..\envs") do (
set ANACONDA_ENVS=%%~fi
)
if not "%1" == "" (
if not exist "%ANACONDA_ENVS%\%1\python.exe" (
echo No environment named "%1" exists in %ANACONDA_ENVS%
goto :eof
)
set ANACONDA_ENV_NAME=%1
set ANACONDA=%ANACONDA_ENVS%\%1
title Anaconda (%ANACONDA_ENV_NAME%^)
) else (
set ANACONDA_ENV_NAME=
for %%i in ("%~dp0..") do (
set ANACONDA=%%~fi
)
title Anaconda
)
set ANACONDA_SCRIPTS=%ANACONDA%\Scripts
for %%i in ("python.exe") do (
for %%j in ("%ANACONDA%\python.exe") do (
if not "%%~f$PATH:i" == "%%~f$PATH:j" (
set ANACONDA_OLD_PATH="%PATH%"
set PATH=%ANACONDA%;%ANACONDA_SCRIPTS%;%PATH%;
echo Added %ANACONDA% and %ANACONDA_SCRIPTS% to PATH.
)
)
)
if not "%ANACONDA_ENV_NAME%" == "" (
echo Activating environment %ANACONDA_ENV_NAME%...
set PROMPT=[%ANACONDA_ENV_NAME%] $P$G
)
I have very little experience with bat language but I guess there may be something to do with this line
setlocal enableextensions enabledelayedexpansion
I tried to remove that line but kept trapped in the ERRORLEVEL 1 expression with message.
error: unable to enable command extensions
Can anyone suggest what I should do to make this bat-file work properly?
I don't think you need a batch file. Assuming that Anaconda and CMD are on your path (which they should be), you can try this as an alternative (it is what I do):
cmd "/c activate py3k && ipython --pylab"
How can I start a file with an associated non-default command (shell verb) like "edit", "print", ... from command-line or from a .bat script by using standard Windows means.
(Those extra actions which you get offered on top upon right-click on a file in the Windows Explorer.)
Thus getting the effect of
python -c "import os;os.startfile('somepic.png', 'edit')"
(ShellExecuteEx), but without using extra tools like python, powershell, or so.
The START command does not seem to offer that.
As learned from the comments and after further searching: there seems to be no direct command for that task in standard Windows indeed.
However using a VBScript snippet should be highly compatible and have lowest system requirements. (Works on all machines here directly - from XP - unlike JScript)
VBScript has been installed by default in every desktop release of
Microsoft Windows since Windows 98;1 in Windows Server since Windows
NT 4.0 Option Pack;[2] and optionally with Windows CE (depending on
the device it is installed on).
Example script shellexec.vbs :
' shellexec.vbs : starts a file using a (non-default) shell verb like "EDIT"
' Usage: shellexec.vbs FILE VERB
' Example: shellexec.vbs demo.png EDIT
fn = WScript.Arguments(0)
cmd = WScript.Arguments(1)
Wscript.Echo "ShellExecute """ + cmd + """ on " + fn
CreateObject("shell.application").ShellExecute fn, "", "", cmd, 1
Use from command-line or batch-file:
shellexec.vbs demo.png EDIT
or:
cscript.exe //Nologo shellexec.vbs demo.png EDIT
An example to show how to do it with an one-liner:
mshta vbscript:Execute("CreateObject(""shell.application"").ShellExecute""%SystemDrive%\autoexec.bat"","""","""",""edit"",1:close")
It will open the dummy autoexec.bat file with the application defined to edit .bat files (by default, Notepad).
It is possible to do with batch code what is done by command START for default action of opening a file with associated application.
In the commented batch code below the shell verb must be specified in third line being assigned to environment variable ActionCommand.
The name of the file to edit, printto, ... must be specified as first parameter of the batch file.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "ActionCommand=edit"
rem Check if batch file was started with name of an existing file.
if "%~1" == "" set "ErrMsg=No file name specified as argument on starting %~nx0" & goto OutputError
if exist "%~1\" set "ErrMsg="%~f1" is a directory and not a file" & goto OutputError
if not exist "%~f1" set "ErrMsg=A file "%~f1" does not exist" & goto OutputError
rem Check if specified file has a file extension. Files starting with . and
rem not containing at least a second . are also files with no file extension.
if "%~n1" == "" set "ErrMsg=File "%~f1" has no file extension" & goto OutputError
if "%~x1" == "" set "ErrMsg=File "%~f1" has no file extension" & goto OutputError
rem On Windows Vista and later REG.EXE outputs without version info for example:
rem HKEY_CLASSES_ROOT\.txt
rem (Default) REG_SZ txtfile
rem There are only spaces used to separate value name, value type and value string.
rem But REG.EXE version 3.0 outputs on Windows XP with version info for example:
rem ! REG.EXE VERSION 3.0
rem
rem HKEY_CLASSES_ROOT\.txt
rem <NO NAME> REG_SZ txtfile
rem NOTE: There are 4 indent spaces and 2 separating tabs in REG 3.0 output line.
rem So either token 2 or token 3 contains value type REG_SZ
rem used to identify the line with the wanted information.
set "TypeToken=2"
rem Get name of registry key associated with extension of specified file.
:GetAssociatedKey
for /F "skip=1 tokens=%TypeToken%*" %%A in ('%SystemRoot%\System32\reg.exe query "HKCR\%~x1" /ve 2^>nul') do (
if "%%A" == "REG_SZ" set "KeyName=%%B" & goto GetCommand
if "%%A" == "NAME>" set "TypeToken=3" & goto GetAssociatedKey
)
set "ErrMsg=No file assocation found for %~x1 in registry" & goto OutputError
:GetCommand
for /F "skip=1 tokens=%TypeToken%*" %%A in ('%SystemRoot%\System32\reg.exe query "HKCR\!KeyName!\shell\%ActionCommand%\command" /ve 2^>nul') do (
if "%%A" == "REG_SZ" set "ActionCommand=%%B" & goto PrepareCommand
if "%%A" == "REG_EXPAND_SZ" set "ActionCommand=%%B" & goto PrepareCommand
)
set "ErrMsg=No edit command found for %~x1 in registry" & goto OutputError
rem Replace "%1" or %1 by full name of specified file in double quotes or
rem append a space and full name of specified file if the command string
rem does not contain "%1" or %1 at all. Then expand the command string.
:PrepareCommand
set "ActionCommand=!ActionCommand:"%%1"="%~f1"!"
set "ActionCommand=!ActionCommand:%%1="%~f1"!"
if "!ActionCommand:%~f1=!" == "!ActionCommand!" set "ActionCommand=!ActionCommand! "%~f1""
call set "ActionCommand=%ActionCommand%"
rem Run the command with current directory set for the application to folder
rem of specified file without checking if the executable file exists at all.
rem Command start displays an error message box which must be confirmed by
rem the user by a click on button OK and outputs the error message also to
rem console if the executable to start could not be found.
start "" /D"%~dp1" %ActionCommand%
endlocal
goto :EOF
:OutputError
echo %~f0
echo.
echo Error: !ErrMsg!.
echo.
echo Press any key to exit batch processing ...
endlocal
pause >nul
This batch file might not work for all possible action commands, but it should work for 99.5% of all edit, printto, ... commands.
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 /?
for /?
goto /?
if /?
pause /?
reg query /?
rem /?
set /?
setlocal /?
start /?
Not sure if this is what you are looking for, but using the START command opens the file I want to edit in the default program.
START "" "Mypdf.pdf"
START "" "Myfile.txt"
START "" "Myjpg.jpg"
ETCETERA ETCETERA........
I need to create a batch file that run this command
start chrome
The problem is that I'm not sure that on the machine there is Google Chrome installed. I can't rely on the registry because I will not have admin permissions.
If I run this command on a machine where Chrome is not installed I get this error dialog
(you see "chromex". I used this name to simulate the absence of the software).
Is there a way to avoid to show this dialog?
Next code snippet could help:
#ECHO OFF >NUL
SETLOCAL enableextensions
SET "_chromePath="
If DEFINED programfiles(x86) (
For /F "tokens=*" %%G in (
'where /R "%programfiles(x86)%" chrome.exe 2^>NUL'
) do SET "_chromePath=%%G"
)
If NOT DEFINED _chromePath (
For /F "tokens=*" %%G in (
'where /R "%programfiles%" chrome.exe 2^>NUL'
) do SET "_chromePath=%%G"
)
If DEFINED _chromePath (
echo start "" "%_chromePath%"
) else (
echo chrome.exe not found
)
Note start "" "%_chromePath%" is echoed merely for debugging purposes only.
Resources (required reading):
An A-Z Index of the Windows CMD command line
Windows CMD Shell Command Line Syntax
#echo off
echo Enter 1 to start up Chrome
set /p input=Type here:
if %input%==1 goto chrome
:chrome
echo Starting chrome...
start chrome.exe
pause
The dialog comes from using Start. Execute files directly to see the command prompt's equivlent.
'cat.exe' is not recognized as an internal or external command,
operable program or batch file.
Normally one would open the web site and windows will use the user's choice of browser.
Start "" www.microsoft.com
start "" "c:\windows\help\mmc\htm\mmc_1.htm"
I can't rely on the registry because I will not have admin permissions.
You have read access to most of the registry as a user and you can override most settings and file associations on a per user basis.