LoginSignup
13
8

More than 3 years have passed since last update.

WindowsのTreeコマンドで階層指定ができなかったのでPowershellで作ってみた。

Last updated at Posted at 2019-07-23

WindowsのTreeコマンドで階層指定したい。

WindowsのTreeコマンド

tree

と書けば現在のディレクトリ配下をツリー表示してくれる。

階層指定する場合

下記のように書くと階層指定できる

tree | findstr /R /C:"^├" /C:"^│  ├" /C:"^│  └" /C:"^└"

参考サイト:Windowsのtreeコマンドで2階層目までだけを表示する方法

ただ、これだと一旦、treeコマンドで全階層をなめてから表示をフィルタリングするので、フォルダ階層が深かったりするととっても遅い。

Powershellで書いてみる

標準では実現できないっぽかったので、Powershellで書いてみた。

Param(
    [Parameter()][String]$Path = (Convert-Path .) ,
    [Parameter()][int]$Depth = 99
) 
Write-Host 
Write-Host "---------------------------------------"
Write-Host "対象パス:"$Path 
Write-Host "深さ:"$Depth
Write-Host "---------------------------------------"
$Output =""
function GetAclAndChildDirRoot($RootDir){

    Write-Host (Split-Path -Leaf $RootDir)
    $Children = Get-ChildItem -Path $RootDir -Force -Directory | select-object fullname
    foreach ($Child in $Children) {
        $i = 1
        GetAclAndChildDir $Child.FullName $i
    } 
}

function GetAclAndChildDir($CurrentTarget,$i){

    if($i -gt $Depth){
        return;
    }
    $Output=""
    for($j=0;$j -lt $i;$j++){
        $Output+=" "
    }

    $Output+=Split-Path -Leaf $CurrentTarget
    Write-Host $Output

    $children = Get-ChildItem -Path $CurrentTarget -Force -Directory | select-object fullname
    $i++
    foreach ($child in $children) {
        GetAclAndChildDir $child.FullName $i
    } 
}


GetAclAndChildDirRoot $Path
Write-Host "---------------------------------------"
Read-Host 

実行するときは、下記のような感じ

.\Tree.ps1 C:\Folder 3

13
8
1

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
13
8