枯木逢春-我于北京
648 字
3 分钟
修改文件时间戳,将其设置为文件内 frontmatter 中 published 和 updated 属性的时间
创建脚本文件 (update-file-timestamps.ps1)
# PowerShell 脚本:批量修改当前目录及子目录下所有 Markdown 文件的创建和修改时间
# 要求:文件必须包含 frontmatter,且 frontmatter 中必须有 'published' 字段。
# - 文件创建时间 -> 'published' 字段的时间
# - 文件最后修改时间 -> 'updated' 字段的时间 (如果存在), 否则使用 'published' 的时间
# 获取脚本所在的目录
$ScriptRoot = $PSScriptRoot
# 检查目录是否存在
if (-not (Test-Path $ScriptRoot)) {
Write-Error "Script directory does not exist: $ScriptRoot"
exit 1
}
# 递归获取所有 Markdown 文件
$markdownFiles = Get-ChildItem -Path $ScriptRoot -Filter "*.md" -File -Recurse
Write-Host "Found $($markdownFiles.Count) Markdown files in '$ScriptRoot' and its subdirectories."
foreach ($file in $markdownFiles) {
Write-Host "Processing file: $($file.FullName)" -ForegroundColor Yellow
try {
# 读取文件内容
$content = Get-Content -Path $file.FullName -Raw -Encoding UTF8
# 检查文件是否包含带有 'published' 字段的 frontmatter
if ($content -match '(?s)^---\s*\n.*?published:\s*([0-9]{4}-[0-9]{2}-[0-9]{2}).*?\n---') {
$publishedDate = $matches[1]
Write-Host " Found published date: $publishedDate" -ForegroundColor Green
try {
# 1. 设置创建时间
$creationDateTime = [DateTime]::ParseExact($publishedDate, "yyyy-MM-dd", $null)
$file.CreationTime = $creationDateTime
Write-Host " ✓ Successfully updated CreationTime to: $($creationDateTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor Green
# 2. 设置最后修改时间
# 默认为 published 的时间
$file.LastWriteTime = $creationDateTime
# 检查是否有 'updated' 字段
if ($content -match '(?s)^---\s*\n.*?updated:\s*([0-9]{4}-[0-9]{2}-[0-9]{2}).*?\n---') {
$updatedDate = $matches[1]
Write-Host " Found updated date: $updatedDate" -ForegroundColor Green
$lastWriteDateTime = [DateTime]::ParseExact($updatedDate, "yyyy-MM-dd", $null)
$file.LastWriteTime = $lastWriteDateTime
Write-Host " ✓ Successfully updated LastWriteTime to: $($lastWriteDateTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor Green
} else {
Write-Host " - No 'updated' field found. LastWriteTime set to published date."
}
}
catch {
Write-Warning " ✗ Cannot parse date: $($_.Exception.Message)"
}
}
else {
# 如果没有找到 'published' 字段,则跳过此文件
Write-Host " - Skipping file: No 'published' field found in frontmatter."
}
}
catch {
Write-Error " ✗ Error processing file: $($_.Exception.Message)"
}
Write-Host ""
}
Write-Host "Batch update completed!" -ForegroundColor Cyan
运行
powershell -ExecutionPolicy Bypass -File "update-file-timestamps.ps1"
修改文件时间戳,将其设置为文件内 frontmatter 中 published 和 updated 属性的时间
https://blog.fuxieyi.top/posts/修改文件时间戳将其设置为文件内-frontmatter-中-published-和-updated-属性的时间/