首页 > 解决方案 > Windows 批处理脚本:查找目录中最后一个文件夹的名称

问题描述

我正在编写一个批处理文件以将文件夹的内容复制到具有新名称的同一目录中的文件夹中。我希望命名约定为: 2021000-Template (这是从中复制文件的位置) 2021001-CompanyA 2021002-CompanyB 等

我提示输入公司名称,但被困在最后一部分。

如何在目录中找到最后一个文件夹的名称,将 202100x 存储在变量中并添加 1?

之后我需要将新变量包含在带有 cname 的字符串中,但我想我可以弄清楚。

谢谢你的帮助!

@echo off
:: CD to correct folder and year in the root
CD\Estimates\2021 

:: Asks for user input on company name and stores it in the cname var
Set /P "cname= Enter Company Name (without spaces): "

:: Copying the entire contents of the Template folder to a new folder named the cname
XCOPY C:\Estimates\2021\2021000-Template C:\Estimates\2021\%cname% /S /I

:: Opens the new folder
start C:\Estimates\2021\%cname%

标签: batch-filedirectoryfind

解决方案


for /f "delims=-" %%a in ('dir /b /ad /on C:\Estimates\2021\2021*-*') do set /a last=%%a+1
echo next subdirectory to be created is "%last% - %cname%"

应该做这项工作,假设没有子目录名称以不符合您的模式开始2021并且名称中包含 a 。-

该命令以名称顺序 ( ) 的基本形式(仅名称)生成与模式“2021 - ”匹配的dir目录 ( ) 列表。(这是隐式的)依次选择每个目录名中的第一个标记,由so分隔,将被分配, ,依此类推 - 按此顺序。将数字加 1,因此是序列中的下一个数字。以这种方式,当循环结束时选择下一个可用的数字,即使数字由于某种原因已被删除。/ad/onsomethingsomethingelsetokens=1-%%a2021000 2021001 2021002 set /afor


推荐阅读