Batch file 如何在内部for循环外部使用批处理文件变量

Batch file 如何在内部for循环外部使用批处理文件变量,batch-file,scripting,Batch File,Scripting,我不熟悉批处理脚本变量范围。但由于缺乏批处理脚本经验,我遇到了范围界定问题 for /f %%i in ('dir /s /b "%FolderLocation%"') do ( set fullpathandfilename=%%i :: For %%A in ("%fullpathandfilename%") do ( Set File=%%~nxA echo %%File :: this would work and print out only filename ) echo %File

我不熟悉批处理脚本变量范围。但由于缺乏批处理脚本经验,我遇到了范围界定问题

for /f %%i in ('dir /s /b "%FolderLocation%"') do (
set fullpathandfilename=%%i ::
For %%A in ("%fullpathandfilename%") do (
Set File=%%~nxA
echo %%File :: this would work and print out only filename
)
echo %File% ::this will not have filename I extracted above
)

那么,如何在内部for循环之外使用%%File呢

setlocal enabledelayedexpansion

for /f %%i in ('dir /s /b "%FolderLocation%"') do (
For %%A in ("%%~i") do (
Set File=%%~nxA
echo !File!
)
:: This shows how "%" doesn't work but "!" does
Echo ^%File^%: %File%   -   ^!File^!: !File!
)

这应该对你有用。只要记住使用
!文件在for循环内部,而
%File%
在外部。

很有趣。这很有效。我首先用setfullpathandfilename=%%I和!文件不起作用。然后我尝试了你的解决方案,它有%%~我做了!文件工作再次感谢。默认情况下,
%%i
包含引号,将等同于:
“i的值”
。如果使用
%%~i
它会删除周围的引号:
“%%~i”
“i的值”