问题描述
我已经尝试了这段代码,但是当我尝试运行它时,当我转到该部分时,cmd窗口将关闭.应该在该目录中列出扩展名为.json的文件.代码可能有问题吗?
I have tried this code but when I try to run it, as I go to that portion the cmd window just closes. It is supposed to list the files with .json extension in that directory. Probably something wrong with the code?
:TrackPrevious
cd /D "%USERPROFILE%\Desktop\"
echo.> "%USERPROFILE%\Documents\fileslist.txt"
for %%G IN ('dir /a-d /b /s') do
echo %%~nxg > fileslist.txt
)
for /F "delims=" %%G IN (fileslist.txt) do (
set DeviceList=%%G
)
echo %Devicelist%`
推荐答案
代码可能有问题吗?
您的代码中有很多错误.
Probably something wrong with the code?
There are many errors in your code.
echo.> "%USERPROFILE%\Documents\fileslist.txt"
上面的fileslist.txt
与在批处理文件的其余部分中使用的fileslist.txt
不同,因为它是在不同的目录中创建的.该行可以从批处理文件中删除,因为它不需要.
The above fileslist.txt
is not the same fileslist.txt
as used in the rest of the batch file as it is created in a different directory. This line can be removed from the batch file as it is not needed.
for %%G IN ('dir /a-d /b /s') do
上面的内容在for
之后缺少/f
,在行的末尾缺少(
.
The above is missing a /f
after for
and a (
at the end of the line.
echo %%~nxg > fileslist.txt
上面的内容是g
而不是G
和>
而不是>>
The above has g
instead of G
and >
instead of >>
echo %Devicelist%`
上面有一个结尾的`
,可能不应该在后面.
The above has a trailing `
which probably shouldn't be there.
它可能也应该在第二个for
循环内,在这种情况下,延迟扩展应与!Devicelist!
一起使用.
It probably should also be inside the second for
loop, in which case delayed expansion should be used together with !Devicelist!
.
我已修复了错误(请参见下文),但仍需要进一步的工作.
I've fixed the errors (see below), but it still requires further work.
目前尚不清楚您实际上要达到什么目的,并且损坏的批处理文件与您的问题的标题不匹配.
It is unclear what you are actually trying to achieve and your broken batch file doesn't match the title of your question.
test.cmd:
@echo off
setlocal enabledelayedexpansion
:TrackPrevious
cd /D "%USERPROFILE%\Desktop\"
rem echo.> "%USERPROFILE%\Documents\fileslist.txt"
for /f %%G IN ('dir /a-d /b /s') do (
echo %%~nxG >> fileslist.txt
)
for /F "delims=" %%G IN (fileslist.txt) do (
set DeviceList=%%G
echo !Devicelist!
)
endlocal
进一步阅读
- Windows CMD命令行的AZ索引-与Windows cmd行相关的所有内容的绝佳参考.
- enabledelayedexpansion -延迟扩展会导致变量在执行时而不是在解析时进行扩展
- 用于/f -根据另一个命令的结果循环命令.
- 参数-命令行参数(或参数)是传递给批处理脚本.
- 重定向-重定向运算符.
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
- for /f - Loop command against the results of another command.
- parameters - A command line argument (or parameter) is any value passed into a batch script.
- redirection - Redirection operators.
Further Reading
这篇关于如何批量列出具有特定扩展名(.json,.txt等)的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!