如何在批处理文件中提供相对路径?

时间:2012-05-23 00:06:34

标签: batch-file

我遇到了以下批处理脚本的问题,我必须在批处理文件中给出硬编码路径的相对路径。

下面是我的soapUI cmd行执行文件,其中soapui-settings.xml是包含我所有soap设置的文件,project.xml是我的testcases。我这里有硬编码路径。因为我要检查这个文件,如果任何其他人执行这个文件将无法工作,因为他们的机器上不存在该路径。我如何在Windows上实现这一目标?有没有办法可以在我的批处理文件中使用硬编码的相对路径并运行它?

这是我的示例文件:

cd C:\soapui4.5\soapUI-Pro-4.5.0\bin  
testrunner.bat -tC:\Users\jvihol\soapui-settings.xml C:\Users\jvihol\Documents\April-RTM-soapui-project.xml

任何帮助都会非常感激。谢谢。 :)

3 个答案:

答案 0 :(得分:5)

这是我用来解决变化路径的技巧。简而言之,

  1. 创建相对于批处理文件位置的所有路径,并
  2. 使批处理文件更改其自己的工作目录。
  3. 如果您调用的工具位于路径中,或者位于由环境变量定义的位置,则会有所帮助。

    这样的事情:

    @echo off
    
    pushd %~dp0
    
    REM Here you are executing in the same directory as the batch file
    REM You can make your path relative to here
    
    popd
    

    对于您的项目,您可以使用相同的%~dp0作为绝对路径的占位符。

    pushd C:\soapui4.5\soapUI-Pro-4.5.0\bin 
    testrunner.bat -EDefault -I -t%~dp0soapui-settings.xml %~dp0April-RTM-soapui-project.xml
    popd
    

答案 1 :(得分:1)

从相对路径获取绝对路径需要有人进行一些计算。我知道的三个选项是:i)一个附加程序,它只做路径计算,ii)使用“当前目录”,和iii)将两个路径粉碎在一起。以下是方法ii)和iii)的粗略说明:

REM example "givens"
set DRIVE=C:
set ROOTPATH=\fee\fie\fo
set RELPATH=funky\stuff
set FILENAME=blarf.txt

REM method ii) using the "current directory" functionality
%DRIVE%
cd %ROOTPATH%
cd %RELPATH%
more %FILENAME%

REM method iii) using explicit concatenation
set FULLPATH=%DRIVE%%ROOTPATH%\%RELPATH%
set PATHFILENAME=%FULLPATH%\%FILENAME%
more %PATHFILENAME%

REM DOS/BAT handling of drive letter is odd (is it part of the path, or not?)
REM It may be necessary to use "cd /D ..."

REM Path calculations are easier 
REM so long as DOS/BAT understands that "\\" is the same as "\"

答案 2 :(得分:0)

也许你想要这个:

cd C:\soapui4.5\soapUI-Pro-4.5.0\bin  
testrunner.bat -t%USERPROFILE%\soapui-settings.xml %USERPROFILE%\Documents\April-RTM-soapui-project.xml

USERPROFILE是一个系统环境变量,包含当前用户主目录的路径。在您的会话中,它将评估为

C:\Users\jvihol

和其他人一样,

C:\Users\someone else's user name