Files
blog/add_pid_to_posts.ps1
T
2026-01-20 21:13:24 +08:00

65 lines
1.8 KiB
PowerShell

# 脚本功能:批量给现有 Markdown 文章添加 pid 字段,按发布时间升序排列(1, 2, 3...)
$postsPath = "content/post"
$files = Get-ChildItem -Path $postsPath -Filter "*.md"
Write-Host "正在扫描文章..."
$postData = @()
foreach ($file in $files) {
$content = Get-Content $file.FullName -Raw -Encoding UTF8
# 提取日期
if ($content -match "(?m)^date:\s*([0-9T:-\s]+)") {
$dateStr = $matches[1].Trim()
try {
$date = [DateTime]::Parse($dateStr)
} catch {
$date = $file.CreationTime
}
} else {
$date = $file.CreationTime
}
$postData += [PSCustomObject]@{
Path = $file.FullName
Date = $date
Content = $content
}
}
# 按时间排序
$sortedPosts = $postData | Sort-Object Date
$id = 1
foreach ($post in $sortedPosts) {
$content = $post.Content
# 检查是否已有 pid
if ($content -match "(?m)^pid:\s*\d+") {
# 更新 pid
$newContent = $content -replace "(?m)^pid:\s*\d+", "pid: $id"
} else {
# 插入 pid (在第二个 --- 之前,或者在 layout/title 之后)
# 简单策略:在第一个 --- 后面插入
# 注意:Raw string start with ---
if ($content -match "^---\s*\r?\n") {
$newContent = $content -replace "^---\s*\r?\n", "--`npid: $id`n"
} else {
# 异常情况,直接追加
Write-Host "Skipping $($post.Path) (No front matter found)"
continue
}
}
# 保持 UTF8 编码 (无 BOM 或带 BOM 取决于原文件,这里统一用 UTF8)
[System.IO.File]::WriteAllText($post.Path, $newContent, [System.Text.Encoding]::UTF8)
Write-Host "Updated $($post.Path) with pid: $id"
$id++
}
Write-Host "处理完成!共更新 $($id - 1) 篇文章。"