当ブログサイトの記事専用のスクリプトになります。
ファイル名:Export-DotnetSourceToHtml.ps1
<#
.SYNOPSIS
C#プロジェクトをHTMLへ変換
.EXAMPLE
Export-DotnetSourceToHtml.ps1 | Set-Clipboard
#>
param (
[string]$ProjectPath = "."
)
if ($ProjectPath -eq ".")
{
$ProjectPath = Get-Location
}
function EscapeForHtml {
param ([string]$Text)
return $Text -replace '&', '&' `
-replace '<', '<' `
-replace '>', '>' `
-replace '"', '"' `
-replace "'", ''' `
-replace '\[', '[' `
-replace '\]', ']' `
-replace '_', '_'
}
# .csproj を1つだけ取得
$csprojFile = Get-ChildItem -Path $ProjectPath -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1
if ($csprojFile) {
$projName = $csprojFile.Name
Write-Output ""
Write-Output "ファイル名:$projName"
Write-Output ('<div class="hcb_wrap"><pre class="prism line-numbers lang-xml" data-file="' + $projName + '" data-lang="xml"><code>')
Get-Content $csprojFile.FullName | ForEach-Object { EscapeForHtml $_ } | ForEach-Object { Write-Output $_ }
Write-Output "</code></pre></div>"
}
# 除外対象のディレクトリ名
$excludeDirs = @("bin", "obj", ".vscode")
$pattern = ($excludeDirs -join '|') -replace '\.', '\.' # 正規表現用にエスケープ
$regex = "([\\/])($pattern)([\\/]|$)" # \ または / 区切り
# .cs ファイルをすべて処理
$csFiles = Get-ChildItem -Path $ProjectPath -Filter "*.cs" -Recurse -File |
Where-Object { $_.FullName -notmatch $regex }
foreach ($file in $csFiles) {
$relativePath = $file.FullName.Substring($ProjectPath.Length).TrimStart('\','/')
Write-Output ""
Write-Output "ファイル名:$relativePath"
Write-Output ('<div class="hcb_wrap"><pre class="prism line-numbers lang-csharp" data-file="' + $relativePath + '" data-lang="C#"><code>')
Get-Content $file.FullName | ForEach-Object { EscapeForHtml $_ } | ForEach-Object { Write-Output $_ }
Write-Output "</code></pre></div>"
}
コメント