【发布时间】:2022-11-23 17:01:25
【问题描述】:
我想获取目录中的最新文件并使用其文件名而不带(数数)检查它是否与其余文件具有相同的名称。
如果文件名匹配,将其重命名为 $(Get-Date -Format yyyymmddhhmmss)_$ScreenTitle 并将其移至输出文件夹。
如果没有,什么也不做。
编辑:
这些是来自 Xbox Game Bar 屏幕截图 (Win+Alt+PrtScn) 的默认文件名:
下面的代码工作正常,(感谢@Theo!) 但我发现文件名的时间发生了变化,因此它与正则表达式不匹配。
$ParentFolder = "$env:USERPROFILE\Videos\Captures"
#Set-Location $ParentFolder
# Create an Output Folder wether It's Existing or Not
New-Item $ParentFolder\Output -Force -ItemType Directory | Out-Null
$OutputFolder = ".\Output"
Get-ChildItem -Path $ParentFolder -Filter '*.png' -File | Group-Object {$_.BaseName.Split("(")[0].TrimEnd()} |
Where-Object { $_.Count -gt 1 } | ForEach-Object {
# get the latest file
$newestFile = $_.Group | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$newestFile
If ($newestFile.BaseName -match '^(.+)\s+(\d{2}_\d{2}_\d{4}\s+\d{2}_\d{2}_\d{2}\s+[ap]m).*$') {
$screentitle = $matches[1]
$dateFromFileName = $matches[2] # the date from the filename unaltered like '11_21_2022 10_59_21 AM'
$dateToday = Get-Date -Format "yyyymmddhhmmss"
# create the new filename
$NewFileName = '{0}_[{1}]{2}' -f $dateToday, $screenTitle, $newestFile.Extension
# Move the file with a new name to the destination
Write-Host "Moving file '$($newestFile.Name)' as '$NewFileName'"
$newestFile | Move-Item -Destination (Join-Path -Path $OutputFolder -ChildPath $NewFileName)
}
}
【问题讨论】:
标签: powershell filenames get-childitem