2. 代码逐段解析
初始化:
$projectRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$pagesDir = Join-Path $projectRoot "src\content\pages"
$urls = @()
$urls += [pscustomobject]@{
Loc = 'https://www.dragonrster.cn/'
LastMod = (Get-Date).ToString('yyyy-MM-dd')
}
首页(/)是硬编码添加的,因为它没有对应的 content-*.html 文件,不能被下面的文件扫描逻辑捕获。首页的 lastmod 使用当前日期——因为每次构建首页都会更新(侧边栏内容变化)。
博客页面扫描:
$blogDir = Join-Path $pagesDir 'blog'
if (Test-Path $blogDir) {
$blogFiles = Get-ChildItem (Join-Path $blogDir 'content-*.html')
| Sort-Object Name
foreach ($file in $blogFiles) {
$baseName = $file.BaseName -replace '^content-', ''
$loc = "https://www.dragonrster.cn/blog-$baseName.html"
$lastMod = $file.LastWriteTime.ToString('yyyy-MM-dd')
$urls += [pscustomobject]@{
Loc = $loc
LastMod = $lastMod
}
}
}
扫描逻辑的几个要点:
只扫描中文博客目录(blog/),不包括 blog/en/ 下的英文文章
文件名 content-{slug}.html → URL /blog-{slug}.html
使用 $file.LastWriteTime 而非内容元数据中的日期——因为文件的修改时间反映了内容实际的最后更新时间
文件按名称排序,确保 sitemap 中的 URL 顺序稳定
|