一旦该行if %lastChar% == \" (
被扩展(变量替换为值),你得到的if \" == \" (
是不是一个有效的条件,所以不需要括号。
使用分配给 appRoot 的值,您最好的选择是直接检查不是最后一个而是前一个字符
set "lastChar=%appRoot:~-2,1%"
if %lastChar% == \
或者,如果您可以更改 appRoot 的值
set "appRoot=C:\test\"
REM grab the last character
set lastChar=%appRoot:~-1%
if %lastChar% == \ (
echo It works!
)
编辑以适应评论
由于 OP 无法控制如何将路径分配给变量,因此可能的情况是:形式为 、 或 的变量set var=
(如果不存在特殊字符set var="path"
,我们可以假设最后两个是等效的)。带或不带尾随反斜杠。路径中有或没有空格。并且需要获得正确的路径(好看,存在与否,这将在稍后检查),没有尾随反斜杠和(不是在 OP 问题中,但应该是)以一致的方式有或没有引号。set var=path
set "var=path"
所以,我们走吧
@echo off
setlocal enableextensions
set "appRoot=c:\some where\"
call :cleanToFullPath appRoot
echo %appRoot%
set "appRoot=c:\some where"
call :cleanToFullPath appRoot
echo %appRoot%
set appRoot="c:\some where\"
call :cleanToFullPath appRoot
echo %appRoot%
set appRoot="c:\some where\a\"
call :cleanToFullPath appRoot
echo %appRoot%
set appRoot=c:\some where\in a rare place
call :cleanToFullPath appRoot
echo %appRoot%
set appRoot=""
call :cleanToFullPath appRoot
echo %appRoot%
goto :EOF
:cleanToFullPath variableName
rem Prepare environment
setlocal enableextensions enabledelayedexpansion
rem get variable name
set "_varName=%~1"
rem get value of variable
set "_tmp=!%~1!"
rem remove quotes from variable value
set "_tmp=%_tmp:"=%"
rem handle empty variables. Default current folder
if not defined _tmp set "_tmp=."
rem prepare to process trailing bar if any
if "%_tmp:~-1%"=="\" set "_tmp=%_tmp%."
rem resolve to full path
for %%# in ("%_tmp%") do set "_tmp=%%~f#"
rem cleanup and update variable
endlocal & set "%~1=%_tmp%"
goto :eof