精简hugo文章发布操作
策略选取:powershell函数 之前情况:创建文章需要切换到hugo目录,再用hugo命令,发布网站则需要3个git命令。 改善之后:创建文章: np ‘文章名’ ; 发布网站: 一、创建文章: 1. 创建powershell配置文件 1 2 3 4 5 6 7 8 # 检查配置文件是否存在 Test-Path $PROFILE # 如果返回 False,创建配置文件 if (!(Test-Path $PROFILE)) { New-Item -Type File -Path $PROFILE -Force Write-Host "已创建 PowerShell 配置文件" -ForegroundColor Green } 2. 记事本打开文件并复制函数 1 2 # 用记事本打开配置文件 notepad $PROFILE PowerShell的函数 a.中文版:存在shell编码与函数编码不一致问题(前者中文编码,后者utf-8) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 function New-Post { param( [Parameter(Mandatory=$true)] [string]$Title ) # 保存当前目录 $currentLocation = Get-Location try { # 设置网站路径(!!!!!! hugo网站的根目录) $websitePath = "C:\Users\amebo\MyFreshWebsite" # 检查目录是否存在 if (-not (Test-Path $websitePath)) { Write-Host "错误:找不到目录 $websitePath" -ForegroundColor Red return } # 检查 Hugo 是否安装 if (-not (Get-Command hugo -ErrorAction SilentlyContinue)) { Write-Host "错误:未找到 hugo 命令" -ForegroundColor Red return } # 切换到网站目录并创建文章(!!!!核心操作:创建md) Set-Location $websitePath Write-Host "正在创建文章: $Title..." -ForegroundColor Yellow hugo new "posts/$Title.md" if ($LASTEXITCODE -eq 0) { Write-Host "成功创建文章:posts/$Title.md" -ForegroundColor Green } else { Write-Host "创建文章失败" -ForegroundColor Red } } finally { # 返回原始目录 Set-Location $currentLocation } } # 设置别名 Set-Alias -Name newpost -Value New-Post Set-Alias -Name np -Value New-Post Write-Host "New-Post 函数已加载!使用方法: np `"文章名称`"" -ForegroundColor Green b. 英文版:不存在编码问题 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 # 1. 创建英文版本的函数内容 $englishContent = @' function New-Post { param( [Parameter(Mandatory=$true)] [string]$Title ) $current = Get-Location $websitePath = "C:\Users\amebo\MyFreshWebsite" if (-not (Test-Path $websitePath)) { Write-Host "Error: Directory not found" -ForegroundColor Red return } if (-not (Get-Command hugo -ErrorAction SilentlyContinue)) { Write-Host "Error: hugo not found" -ForegroundColor Red return } Set-Location $websitePath Write-Host "Creating post: $Title..." -ForegroundColor Yellow hugo new "posts/$Title.md" if ($LASTEXITCODE -eq 0) { Write-Host "Success: posts/$Title.md created" -ForegroundColor Green } else { Write-Host "Failed to create post" -ForegroundColor Red } Set-Location $current } Set-Alias np New-Post Set-Alias newpost New-Post Write-Host "New-Post function loaded. Use: np `"PostTitle`"" -ForegroundColor Green '@ # 2. 保存到配置文件(使用ASCII编码) $englishContent | Out-File -FilePath $PROFILE -Encoding ASCII # 3. 重新加载配置文件 . $PROFILE 效果: ...