在批处理文件脚本中查找通配符列表的最新文件



给定如下目录树:

parent
dir-v0.1.0
subdir
dir-v0.2.0
subdir
dir-v0.3.0  # lacks subdir

我需要一个Windows批处理序列(适用于Win7+(,它的工作方式类似于以下Unix Bash代码:

found=$(ls -dt ../dir-v0.*.0/subdir | head -1)
if [ "$found" ]; then
...
fi

Powershell子命令是一个选项。(遗憾的是,powershell脚本无法在双击时启动。(

命令外壳通配符只能出现在最后一个路径元素中,所以这不起作用:

dir /o:d ..dir-v0.*.0subdir

编辑:这是有效的,使用powershell:

setlocal EnableDelayedExpansion
set findSub=get-item ..dir-v0.*.0subdir ^| ^
sort -property LastWriteTime ^| ^
select -last 1 -expandproperty FullName
set findSub=powershell -noprofile -command "!findSub!"
for /f "delims=" %%V in ('!findSub!') do set found=%%V
if defined found (...)

以下批处理文件可用于获取包含子目录subdir的批处理文件目录的父目录中版本目录的完全限定名,第二个数字是包含子目录subdir的所有版本目录中的最大数量,只要版本字符串中的第二个编号从不包含一个或多个前导零。

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "PreviousVersion=-1"
set "VersionDirectory="
for /D %%I in ("%~dp0..dir-v0.*.0") do if exist "%%Isubdir" (
for /F "tokens=2 delims=." %%J in ("%%~nxI") do (
set "CurrentVersion=%%J"
setlocal EnableDelayedExpansion
if !CurrentVersion! GTR !PreviousVersion! (
endlocal
set "VersionDirectory=%%I"
set "PreviousVersion=%%J"
) else endlocal
)
)
if defined VersionDirectory (
echo Directory with greatest version number containing subdir is:
echo(
echo "%VersionDirectory%"
) else (
echo Could not find any version directory with subdir.
)
echo(
pause
endlocal

如果保证版本目录的路径从不包含一个或多个感叹号,则批处理文件可以更快。

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "PreviousVersion=-1"
set "VersionDirectory="
for /D %%I in ("%~dp0..dir-v0.*.0") do if exist "%%Isubdir" (
for /F "tokens=2 delims=." %%J in ("%%~nxI") do (
if %%J GTR !PreviousVersion! (
set "VersionDirectory=%%I"
set "PreviousVersion=%%J"
)
)
)
if defined VersionDirectory (
echo Directory with greatest version number containing subdir is:
echo(
echo !VersionDirectory!
) else (
echo Could not find any version directory with subdir.
)
echo(
pause
endlocal

在这种情况下,会对整个批处理文件启用延迟扩展。

注意:带有选项/D的命令FOR会忽略具有隐藏属性集的目录。

如果使用的批处理文件应在当前目录的父目录上运行,而与批处理文件的存储位置无关,则删除%~dp0并将set "VersionDirectory=%%I"修改为set "VersionDirectory=%%~fI"

如果版本目录是否已经包含子目录subdir并不重要,则可以删除条件if exist "%%Isubdir"

以下代码可用于获取版本号最大的版本目录的子目录subdir中最新文件的无路径文件名:

set "NewestFile="
for /F "eol=| delims=" %%K in ('dir "%VersionDirectory%" /A-D /B /O-D /TW 2^>nul') do set "NewestFile=%%K" & goto HaveNewestFile
:HaveNewestFile
if not defined NewestFile (
echo Failed to find a file in directory: "%VersionDirectory%"
) else (
echo Newest file in "%VersionDirectory%" is: "%NewestFile%"
)

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在那里执行以下命令,并完整仔细地阅读每个命令显示的帮助页。

  • call /?。。。解释%~dp0。。。驱动器和参数0的路径,该路径是始终以反斜杠结尾的批处理文件目录路径
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • pause /?
  • set /?
  • setlocal /?

最新更新