【发布时间】:2020-09-24 20:33:19
【问题描述】:
我有一个 Windows 批处理脚本,它以三种模式之一运行,具体取决于命令行参数的数量:
1 个命令行参数:播放命名的 .wav 文件
2 个命令行参数:运行第一个命令行参数指定的命令,然后播放第二个命令行参数指定的 .wav 文件
3 个命令行参数:运行第一个命令行参数指定的命令,然后播放通过第二个或第三个命令行参数指定的 .wav 文件,具体取决于命令是否成功
我的问题在于第三种模式:无论命令是否成功,脚本总是播放第一个声音。任何建议将不胜感激。
@ECHO OFF
Setlocal disableDelayedExpansion
:: OVERVIEW
:: This script optionally runs a command and then uses Eli Fulkerson's
:: `sounder.exe` to play the specified or default sound.
:: The Media environment variable must be defined and contain the path of a
:: folder containing one or more .wav files.
:: REFERENCE
:: https://www.elifulkerson.com/projects/commandline-wav-player.php
:: USAGE CASE 1: NO ARGUMENTS
:: If the script is invoked without arguments, it plays the default sound file
:: `beep-05.wav`.
:: USAGE CASE 2: ONE ARGUMENT
:: The single argument is the name of a sound file, minus the .wav extension.
:: sound.bat will play this sound file. Example:
:: sound meow1
:: USAGE CASE 3: TWO ARGUMENTS
:: The first argument contains a command to be run; the second argument is the
:: name of a sound file, minus the .wav extension. sound.bat will play the
:: sound after the command finishes running, regardless of exit code. Example:
:: sound "dir C:\Phillip" meow1
:: USAGE CASE 4: THREE ARGUMENTS
:: The first argument contains a command to be run; the second and third
:: arguments name sound files, minus the .wav extension to be played if the
:: executes successfully or fails, respectively.
:: sound "dir C:\Phillip" meow1 meow2
:: NOTE
:: It is not currently possible to use this scripts to play sound files that are
:: located outside the Media folder.
:: AUTHOR
:: Phillip M. Feldman
:: REVISION HISTORY
:: June 5, 2020, Phillip M. Feldman: Initial version.
If not defined Media (
msg "%username%" The Media environment variable is not defined!
GOTO :EOF
)
If not EXIST %Media% (
msg "%username%" The Media folder '%Media%' does not exist!
GOTO :EOF
)
If '%1' == '' (
:: No command-line arguments.
sounder %Media%\beep-05.wav
GOTO :EOF
)
If '%2' == '' (
:: One command-line argument.
sounder %Media%\%1%.wav
GOTO :EOF
)
If '%3' == '' (
:: Two command-line arguments.
%~1
sounder %Media%\%2%.wav
GOTO :EOF
)
If '%4' == '' (
:: Three command-line arguments.
%~1
If %ERRORLEVEL% == 0 (
sounder %Media%\%2%.wav
) else (
sounder %Media%\%3%.wav
)
GOTO :EOF
)
【问题讨论】:
-
If '%3' == ''是错误的语法。单引号不提供双引号提供的保护,并且如果文件路径参数包含空格并且已通过双引号传递给脚本,则应使用~修饰符If "%~3" == ""此外,您正在错误地扩展参数变量。sounder %Media%\%3%.wav应该是:sounder "%Media%\%~3.wav" -
请删除所有格式错误的标签
::并用正确的评论命令Rem替换它们。 或者更好的是,将它们全部删除,因为我们只需要 minimal reproducible example,我们不需要所有这些。此外,If not EXIST %Media% (无法确定folder是否名为ExpandedValueOfMediaVariableexists。 -
您需要延迟扩展
errorlevel变量或使用if not errorlevel 1
标签: windows batch-file command-line-arguments