开发者

Include a batch file in a batch file

I have a problem calling a batch file from another batch file when trying to run everything by using Process.Start. Basically I call the execution of a batch file from m开发者_高级运维y c# program that looks like this:


call include.bat  

//execute the rest of the batch file here  

The include.bat file sets up paths and can be used by a number of other batch files. When I run the Process.Start sometimes this works and sometimes I get ERROR: cannot find include.bat. First of all any idea why this happens? And ideas on how to fix this from the batch file?


To switch to the directory your batch file is located in, use this:

cd %~dp0

I do this in almost all of my batch scripts. That way relative paths should always work.


I know this is an old question but I thought it would be worth noting that the approach promoted by the accepted answer (i.e. changing the working directory) may not always be appropriate.

A better general approach is to refer to dependencies by full path:

call "%~dp0include.bat"

(Since %~dp0 already ends with a backslash, we don't need to add another one.)

Here are some benefits of not changing the working directory:

  1. The rest of the batch file can still use the original working directory.
  2. The original working directory in the command prompt is preserved, even without "SETLOCAL".
  3. If the first batch file is run via a UNC path (such as "\\server\share\file.bat"), the full-path call will succeed while changing the directory (even with "cd /d") will fail. (Using pushd/popd would handle this point, but they have their own set of problems.)

These benefits are particularly important for alias-type batch files, even if they are not as important for the specific situation that motivated this question.


Before the script, try CD /D %~dp0


First thing I'd try is to use full path information in the call statement for include.bat. If that fixes it, you probably are just not running the batch file from the proper location. I'm sure there's a "working directory" capability in C#, I'm just not sure what it is.


Do you set ProcessStartInfo.WorkingDirectory ( http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx ) on the ProcessStartInfo that you pass to Process.Start?

Since include.bat sometimes cannot be found, working directory may be wrong (not the folder where include.bat is located).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜