LoginSignup
4
5

More than 5 years have passed since last update.

PowerShellでファイルの一覧をMarkdownに出力

Posted at

概要

  1. 未だにOffice系のドキュメント等がいっぱいあるのでGithub等のwikiに載せちゃおう
  2. リンク書くのめんどくさ
  3. 一覧を生成してしまえ

スクリプト

FileList2Markdown.ps1
param(
    [Parameter(Mandatory=$true)]
    [string]
    $TargetPath,

    [string]
    $OutputPath
)
function Convert-Markdown {
    param(
        [Parameter(ValueFromPipeline=$true)]
        [PSObject]
        $TargetInfo,

        [int]
        $Depth=1,

        [Parameter(Mandatory=$true)]
        [string]
        $Parent
    )
    process {
        $row = "#" * ($Depth+1) + " "
        $row += $TargetInfo.Name
        Write-File $row
        if($TargetInfo.PSIsContainer) {
            Get-ChildItem $TargetInfo.FullName | Convert-Markdown -Depth ($Depth+1) -Parent (Join-Path $Parent $TargetInfo.Name)
        } else {
            Get-FileLink -FileName $TargetInfo.Name -ParentDir $Parent | Write-File
        }
    }
}
function Get-FileLink {
    param(
        [Parameter(Mandatory=$true)]
        [string]
        $FileName,

        [Parameter(Mandatory=$true)]
        [string]
        $ParentDir
    )
    $path = Join-Path $ParentDir $FileName
    "[{0}]{{{1}}}`n" -F $FileName, ($path -replace "\\" , "/")
}
function Write-File {
    param(
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [string]
        $Body
    )
    Out-File $OutputPath -Encoding UTF8 -Append -InputObject $Body
}

$title = "# Documents"
if(-not (Test-Path $TargetPath)) {
    throw [System.IO.DirectoryNotFoundException] "$TargetPath not found."
}
$TargetDir = Convert-Path $TargetPath

if(-not (Get-Item $TargetDir).PSIsContainer) {
    $TargetDir = Split-Path $TargetDir -Parent
}

if( -not $OutputPath) {
    $OutputPath = (Split-Path $TargetDir -leaf) + ".md"
}

$null = New-Item $OutputPath -Type file -Force
Write-File $title
Get-ChildItem $TargetDir | Convert-Markdown -Parent (Split-Path $TargetDir -leaf)

構造(INPUT)

...\DOC
|   111.txt
|
\---aaa
    |   bbb.txt
    |
    \---ccc
            ddd.txt

Markdown(OUTPUT)

# Documents
## aaa
### ccc
#### ddd.txt
[ddd.txt](Doc/aaa/ccc/ddd.txt)

### bbb.txt
[bbb.txt](Doc/aaa/bbb.txt)

## 111.txt
[111.txt](Doc/111.txt)

markdown.png

使い方

# .\FileList2Markdown.ps1 -TargetPath {対象ディレクトリ} -OutputPath {出力先}

.\FileList2Markdown.ps1 -TargetPath .\Doc -OutputPath Documents.md
.\FileList2Markdown.ps1 .\Doc # でもOK(Doc.mdに出力される)

pre-commitフックから読んじゃうのもありかと

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5