我可以解析文件名中的字符串以帮助使用 Powershell 在其子文件夹中找到该文件吗?

Can I parse a string from a filename to help find the file in its subfolders with Powershell?

我正在寻找一系列文件,这些文件遵循非常严格的文件名格式,但根据文件名中的字符串位于不同编号的子文件夹中。

  1. 文件名总是“LAX_CA_Baseball_<8 digits>.pdf

  2. 文件总是有 4 个文件夹,最上面的两个文件夹总是 \\fileserver\sports\pdf

  3. 最后 4 位数字始终代表底部的两个子文件夹,例如 LAX_CA_Baseball_12345678.pdf 将位于“\\fileserver\sports\pdf\56\78”

  4. 总共有几千万个文件,光是从\\fileserver\sports\pdf中搜索文件名就需要很长时间

我可以在 powershell 中编写一些东西来解析文件名的最后 4 位数字,将其转换为底部子文件夹,然后获取文件并将其复制到新文件夹吗?

假设你已经有了文件名,你可以提取数字并用正则表达式构造路径:

$f = "LAX_CA_Baseball_12345678.pdf"

if ($f -match ".*_\d{4,4}(\d\d)(\d\d)\.pdf") {
  $sourcePath = "\server\sports\pdf$($matches[1])$($matches[2])$f"
  $destinationPath = "some other folder path"
  Copy-Item $sourcePath $destinationPath 
} else {
  Write-Error "Can't determine folder from filename $f"
}