我有一个批处理文件,我在其中显示目录中的所有 *.pem 文件,让用户可以选择一个,此时只是试图通过使用他们选择的数字来向用户显示他们选择的文件 ECHO数组的内容。我相信不知何故,因为它在 IF 语句内部,索引变量“selectedPem”没有在数组的索引括号中扩展,因为它使用 % 而不是使用延迟扩展!,这似乎在数组的索引中不起作用括号。我认为这是因为如果我在 IF 语句之前设置“selectedPem”变量,它会正确 ECHO。我认为这个工作的唯一选择是以某种方式使用子程序。为什么 selectedPem 变量在 IF 语句中不起作用?
@echo off
setlocal enabledelayedexpansion
set dir=%~dp0
cd %dir%
ECHO Performing initial search of private and public keys...
set pemI=0
set keyI=0
for %%p in (*.pem) do (
REM echo %%~nxp
set pems[%pemI%]=%%~nxp
REM echo !pems[%pemI%]!
set /a pemI=%pemI%+1
)
REM echo %pems[0]%
set /a totalPems=%pemI%-1
REM This is the test selectedPem variable that showed me the variable works
REM if I set it outside
REM of the "if defined pems[0]" statement
REM set selectedPem=
if defined pems[0] (
echo PEM Files Found:
for /l %%p in (0,1,%totalPems%) do (
echo %%p^) !pems[%%p]!
)
ECHO Select a pem file to be used as your private key. Otherwise, press
Q to not select one.
set /P selectedPem=Enter a number or Q:
IF "!selectedPem!"=="q" (
ECHO Skipping private key selection.
) ELSE (
ECHO !selectedPem!
ECHO %pems[0]%
REM The below ECHO only works when the above selectedPem is set
REM outside of the "IF defined" statement
ECHO !pems[%selectedPem%]!
REM Tried these other implementations:
REM ECHO !pems[!!selectedPem!!]!
REM ECHO %pems[!selectedPem!]%
REM setlocal disabledelayedexpansion
REM ECHO %pems[%%selectedPem%%]%
set privatekey=!pems[%selectedPem%]!
ECHO You chose %privatekey%
)
)`
输出:
Performing initial search of private and public keys...
PEM Files Found:
0) brandon.pem
Select a pem file to be used as your private key. Otherwise, press Q to not
select one.
Enter a number or Q:0
0
brandon.pem
ECHO is off.
You chose
我理解“ECHO 已关闭”。而是输出,因为它将我的数组变量引用解释为空。感谢您花时间阅读我的脚本,我可能过于复杂了。