如何在powershell中返回具有相同扩展名但包含名称特定结尾的文件?

问题描述

一个项目文件夹中有多个 .webp 文件。一些.webps 是原始图片,一些用作缩略图(它们的大小不同)。使用的命名约定是:原始文件只称为NAME.webp,而缩略图是NAME-thumb.webp。我正在尝试创建一个 Powershell 脚本,该脚本根据原始文件创建日期返回所有 -thumb.webp 文件。因此,如果原始文件是今天创建的,则返回相应的 -thumb.webp(除了 -thumb

这是我到目前为止所尝试的,但仍有一些问题:

$webps = (Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $_.CreationTime -gt $refdate }).BaseName
$output = Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $webps -contains ($_.BaseName + "-thumb") }

解决方法

Get-ChildItem $dir\*.webp -Exclude *-thumb.webp -File | 
    Where-Object CreationTime -gt $refdate | 
    ForEach-Object { $_.Fullname -replace '\.webp$','-thumb.webp' }

首先我们得到所有 *.webp 文件,不包括 *-thumb.webp 文件。使用 Where-Object 我们只选择 CreationTime 大于 $refdate 的文件。最后,我们将 .webp 替换为 -thumb.webp 以返回缩略图文件的完整路径。

如果您只需要文件名,请将 $_.Fullname 替换为 $_.Name

,

Group-Object 可以提供帮助:

var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g,(e) => {
    out.push(e.replace(':','').replace(';',''))
    return e;
});
console.log(out[0])
  • $refDate = (Get-Date).Date # today's calendar day,for instance. Get-ChildItem -File -Path $dir -Filter *.webp | Group-Object { $_.BaseName -replace '-thumb$' } | # by base name without suffix ForEach-Object { # Test the creation date of the non-thumbnail *.webp file,# which comes alphabetically first in the group. if ($_.Group[0].CreationTime -gt $refDate) { $_.Group[1] # Output the corresponding *-thumb.webp file } } 使用 -replace operator 从文件库名称中删除 -replace '-thumb$' 后缀,以便 -thumb<name>.webp 文件具有相同的<name>-thumb.webp 组合在一起。

  • 上面假设每个 <name> 文件都有一个 <name>.webp 副本,在这种情况下,每个 <name>-thumb.webp 数组包含两个 System.IO.FileInfo 实例,第一个始终代表$_.Group,第二个 <name>.webp 文件,因为 <name>-thumb.webp 按分组标准/a 对组成员进行排序。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...