xxxxxxxx
Bookmark

用PowerShell列出目錄

Get-ChildItem -Recurse -Depth 2 | Select-Object FullName有列出完整路徑,但是我希望是類似tree -L 3輸出的目錄樹與檔名而已。

純 PowerShell 自定義函式 (不需安裝任何工具)。貼入以下代碼:

function Show-Tree {
    param(
        [string]$Path = ".",
        [int]$MaxDepth = 3,
        [int]$CurrentDepth = 0
    )
    if ($CurrentDepth -gt $MaxDepth) { return }

    $items = Get-ChildItem -Path $Path
    foreach ($item in $items) {
        $indent = "  " * $CurrentDepth
        $prefix = if ($item.PSIsContainer) { "[+] " } else { "    " }
        Write-Host "$indent$prefix$($item.Name)"

        if ($item.PSIsContainer) {
            Show-Tree -Path $item.FullName -MaxDepth $MaxDepth -CurrentDepth ($CurrentDepth + 1)
        }
    }
}

執行方式:

Show-Tree -MaxDepth 2

(顯示 3 層)

You save my day!

導讀
選擇語音
1x
* 更改設定將重新朗讀文章。