从其他目录调用此批处理脚本时返回不正确的值。我希望有人可以帮助我解决这个问题,以便它始终确定正确的 APP_HOME 目录。
该脚本位于如下位置:
C:\Temp\MyApplication\bin\runner.bat
而且,我想从以下位置执行它:
C:\Temp\OutsideDir\runApp.bat
当我尝试这个时,我得到 'OutsideDir' 但我希望它得到 'bin' :
C:\Temp\OutsideDir>C:\Temp\MyApplication\bin\runner.bat
Current directory is: C:\Temp\MyApplication\bin
This folder name: OutsideDir
Function arg must match actual folder name.
This script may not be running from the expected folder.
There was an error.
这是脚本:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
TITLE Script %~n0%~x0 running from %~dp0
CALL :getparentfolder bin
ECHO My app home is: %APP_HOME%
GOTO :END
:: function to get parent folder name or APP_HOME of scripts currrent folder
:: function requires current folders name as an arg or it will fail to run
:getparentfolder dirName
SET "BIN_HOME=%~dp0"
IF "%BIN_HOME:~-1%"=="\" SET "BIN_HOME=%BIN_HOME:~0,-1%"
ECHO Current directory is: %BIN_HOME%
FOR /F "tokens=1,* delims=^\" %%I IN ("%BIN_HOME%") DO (
SET THISFOLDER=%%~nxI
)
ECHO This folder name: %THISFOLDER%
IF "%~1"=="%THISFOLDER%" (
SET APP_HOME=!BIN_HOME:\%THISFOLDER%=!
ECHO APP_HOME: %APP_HOME%
) ELSE (
ECHO Function arg must match actual expected folder name.
ECHO This script may not be running from the expected folder.
GOTO :ERROR
)
EXIT /B 0
:ERROR
ECHO There was an error.
PING.exe -n 10 -w 1 127.0.0.1>nul
:END
PING.exe -n 10 -w 1 127.0.0.1>nul
ECHO The script %~n0%~x0 is finished.