批处理脚本 return 最近的文件夹名称与文本文件中的字符串匹配

Batch scripting return most recent folder name with string match in text file

我创建了一个小的批处理脚本,它通过给定根文件夹和 returns 最新创建的顺序名称查看所有文件夹:

@echo off
FOR /F "delims=" %%i IN ('dir C:\RootFolder\FolderName_* /b /ad-h /t:c /o-d') DO (
SET a=%%i
GOTO :found
)
echo No folder found
goto :eof
:found
echo Most recent directory: %a%

现在我必须通过返回包含以下字符串的最新目录来增强它

Name="Test" Value="completed"

在名为 test.xml 的文件 中,其子文件夹名为 test。

F.e。我有

  1. C:\RootFolder\FolderName_1\ --- 今天创建 --- 使用 test\test.xml 但不包含该字符串
  2. C:\RootFolder\FolderName_2\ --- 昨天创建 --- 但没有找到 test\test.xml
  3. C:\RootFolder\FolderName_3\ --- 三天前用 test\test.xml 和
  4. 中的匹配字符串创建
  5. C:\RootFolder\FolderName_4\ --- 四天前创建 test\test.xml 并在
  6. 中匹配字符串

那么应该返回的文件夹是3号。

有什么办法可以实现吗?

提前致谢!

要获取最新创建的目录,使用您的模式,使用 powerShell:

Get-Childitem FolderName_* | sort CreationTimeUTC

再扩展一点,考虑test.xml:

Dir RootFolder_* | 
Sort CreationTimeUtc |
Select -Property FullName, @{Name="XmlFile";Expression={ $_.FullName + "\test.xml"}} |
Where { Test-Path $_.XmlFile } | 
Select FullName, @{Name="XmlContent";Expression={ Get-Content ($_.XmlFile)}} |
Where { $_.XmlContent -match "Value=""completed""" } |
Select -ExpandProperty FullName -First 1

您还可以稍微调整一下,以获取包含您的模式的最新 xml 文件:

Dir RootFolder_*\test.xml | 
Where { Test-Path $_.FullName } | 
Select FullName, @{Name="XmlContent";Expression={ Get-Content ($_.FullName)}} |
Where { $_.XmlContent -match "Value=""completed""" } |
Select -First 1

我想我宁愿使用通配符和 Select-String cmdlet 在 PowerShell 中执行此操作。我会在管道后面换行和缩进以便于阅读,因为这很长。

Get-ChildItem 'C:\RootFolder\FolderName_*\Test\Test.xml' |
    Where{(Select-String -simplematch 'Name="Test" Value="completed"' -quiet)} |
    Select -Expand Parent |
    Select -Expand Parent |
    Sort -Descending LastWriteTime |
    Select -First 1

所以让我们逐行分解:

  1. Get-ChildItem 获取存储在您文件夹的 "test" 子文件夹中的所有 Test.xml 文件的文件对象。
  2. 然后输入 Where 语句,使用 Select-String-Quiet 开关在这些文件中搜索字符串 'Name="Test" Value="completed"',因此 Select-String 仅输出 True/False 取决于它是否在文件中找到该字符串。因此 Where 语句只传递那些包含管道中字符串的文件。
  3. 接下来我们展开 Parent 属性,为我们提供存储每个文件的 'Test' 文件夹。
  4. 然后我们再做一次,给我们 'FolderName_*' 文件夹,'Test' 文件夹存储在其中。
  5. 然后我们按 LastWriteTime 排序。
  6. 最后我们select第一个。

就是这样,它为您提供了您正在寻找的文件夹对象,您可以随意使用(移动它、重命名它、简单地显示它,等等)。