Windows 批处理调用命令没有传递变量值?

Windows 批处理调用命令没有传递变量值?

运行我的脚本时出现奇怪的输出:

@echo off
setlocal
pushd "%~dp0"

set Mode=batch

if "%Mode%"=="batch" call :BATCH
echo %Loc%
pause>nul
exit

:BATCH
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
setlocal enabledelayedexpansion
set Loc=!folder!
Goto:eof

它应该显示我选择的文件夹位置。但我得到的却是回声关闭。

答案1

运行脚本时出现奇怪的输出

要调试批处理脚本,请注释掉该@echo off行,以便查看正在发生的事情:

rem @echo off

你的setlocal enabledelayedexpansion位置不对。将其移至文件开头。

测试.cmd:

@echo off
setlocal
setlocal enabledelayedexpansion
pushd "%~dp0"

set Mode=batch

if "%Mode%"=="batch" call :BATCH
echo %Loc%
pause>nul

:BATCH
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
set Loc=!folder!
Goto:eof

示例输出(我选择“桌面”):

F:\test>test
C:\Users\DavidPostill\Desktop

F:\test>

笔记:

  • ECHO is off.如果第一次显示对话框时您按“取消”,则仍会显示。

相关内容