打印目录树,但排除Windows cmd上的文件夹 [英] Print directory tree but exclude a folder on windows cmd

查看:152
本文介绍了打印目录树,但排除Windows cmd上的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要打印除文件夹外的目录树。我已经知道像这样打印树的基本方法:

  tree / A> tree.txt 

我想要实现以下目标:

  tree / A [不包含文件夹node_modules]> tree.txt 


解决方案

cmd。 exe 的内部 tree 命令不支持排除目录。




  • 如果只需要排除名称​​本身 而不是整个子树的目录 (子目录及其后代),请参见 nferrell的答案


  • 如果您需要排除与给定名称匹配的目录的整个子树 ,则需要做更多的工作-请参见




以下是PowerShell函数 tree的源代码,它模仿 cmd.exe tree 命令的行为,同时: p>


  • 按名称提供对子树的选择性排除

    注意:您可以指定多个名称,用<$ c $分隔c>,和名称可以是通配符模式-请注意,它们仅适用于目录名称,但是不适用于完整路径。


  • 提供跨平台支持

    注意:确保使用UTF-8编码的 BOM 保存脚本,以使脚本在没有 -Ascii的情况下正常运行。 code>。


  • 提供开关 -IncludeFiles 来同时打印文件




加载以下函数后,所需命令如下:

  tree-排除node_modules -Ascii> tree.txt 

运行 tree-?获取帮助树了解更多信息。






  ###`tree`源代码(例如,添加到`$ PROFILE`中; PSv4 +):

函数树{
<#
.SYNOPSIS
打印目录的子树结构,可以选择包含排除项。 #'

.DESCRIPTION
以树形形式
递归打印给定目录的子目录结构,以可视化类似于cmd.exe内置
的目录层次结构'tree'命令,但具有按目录
名称排除子树的附加功能。

注意:不遵循指向目录的符号链接;警告是发出


.PARAMETER路径
目标目录路径;默认为当前目录。
您可以指定一个通配符模式,但是它必须解析为一个目录。

.PARAMETER排除
应该从输出中排除的一个或多个目录名;允许使用通配符
。与目标层次结构
中的任何位置匹配的任何目录及其子树均被排除。
如果还指定了-IncludeFiles,则排除项也将应用于文件的
名称。

.PARAMETER IncludeFiles
默认情况下,只打印目录;使用此开关也可以打印文件


.PARAMETER Ascii
使用ASCII字符可视化树结构;默认情况下,使用OEM字符集中的图形
字符。

.PARAMETER IndentCount
指定用于表示层次结构每个级别的字符数。
默认为4。

.PARAMETER强制
在输出中包括隐藏的项目;默认情况下,它们会被忽略。

。注意
不遵循目录符号链接,而是发出警告。

。示例


打印当前目录的子目录层次结构。

.EXAMPLE
树〜/ Projects -Ascii -Force-排除node_modules,.git

使用ASCII字符
打印指定目录的子目录层次可视化,包括隐藏的子目录,但不包括名为 node_modules或 .git的任何目录的
子树。

#>

[cmdletbinding(PositionalBinding = $ false)]
param(
[parameter(Position = 0)]
[string] $ Path ='。',
[string []] $ Exclude,
[ValidateRange(1,[int] :: maxvalue)]
[int] $ IndentCount = 4,
[switch] $ Ascii,
[开关] $ Force,
[开关] $ IncludeFiles


#嵌入式递归辅助函数,用于绘制树。
函数_tree_helper {

param(
[string] $ literalPath,
[string] $ prefix


#获取所有子目录。并根据要求提供文件。
$ items = Get-ChildItem -Directory:(-not $ IncludeFiles)-LiteralPath $ LiteralPath -Force:$ Force

#应用排除过滤器(如果已指定)。
if($ Exclude -and $ items){
$ items = $ items.Where({$ name = $ _。Name; -not $ Exclude.Where({$ name -like $ _} ,'First')})
}

if(-not $ items){return}#没有子目录。 /文件,我们已经完成了

$ i = 0
foreach($ item中的$ items){
$ isLastSibling = ++ $ i -eq $ items.Count
#打印此目录。
$ prefix + $(如果(($ isLastSibling){$ chars.last} else {$ chars.interior})+ $ chars.hline *($ indentCount-1)+ $ item.Name
#递归,如果它是子目录(而不是文件)。
if($ item.PSIsContainer){
if($ item.LinkType){写警告不遵循目录符号链接:$ item;继续}
$ subPrefix = $ prefix + $(if($ isLastSibling){$ chars.space * $ indentCount} else {$ chars.vline + $ chars.space *($ indentCount-1)})
_tree_helper $ item.FullName $ subPrefix
}
}
}#函数_tree_helper

#用来绘制结构的字符哈希表
$ ndx = [布尔] $ Ascii
$ chars = @ {
内部=('├','+')[$ ndx]
last =('└','\') [$ ndx]#'
hline =('─','-')[$ ndx]
vline =('│','|')[$ ndx]
space = ''
}

#将路径解析为完整路径,并验证其存在和预期的类型。
$ literalPath =(解析路径$ Path).Path
if(-不是$ literalPath-或-not(Test-Path -PathType容器-LiteralPath $ literalPath)-或$ literalPath.count -gt 1){抛出'$ Path'必须解析到单个现有目录。}

#打印目标路径。
$ literalPath

#调用辅助函数以绘制树。
_tree_helper $ literalPath

}


I want to print a directory tree excluding a folder. I already know the basic way to print the tree like this:

tree /A > tree.txt

I want to achieve something like this:

tree /A [exclude folder node_modules] > tree.txt

解决方案

cmd.exe's internal tree command does not support excluding directories.

  • If you only need to exclude directories by name themselves and not also their entire subtree (child directories and their descendants), see nferrell's answer.

  • If you need to exclude the entire subtree of directories matching a given name, more work is needed - see below.

Below is the source code for PowerShell function tree, which emulates the behavior of cmd.exe's tree command, while also:

  • offering selective exclusion of subtrees by name
    Note: You may specify multiple names separated by , and the names can be wildcard patterns - note that they only apply to the directory name, however, not the full path.

  • offering cross-platform support
    Note: Be sure to save your script with UTF-8 encoding with BOM for the script to function properly without -Ascii.

  • offering switch -IncludeFiles to also print files.

With the function below loaded, the desired command looks like this:

tree -Exclude node_modules -Ascii > tree.txt

Run tree -? or Get-Help tree for more information.


### `tree` source code (add to your `$PROFILE`, for instance; PSv4+):

function tree {
  <#
  .SYNOPSIS
  Prints a directory's subtree structure, optionally with exclusions.                        #'

  .DESCRIPTION
  Prints a given directory's subdirectory structure recursively in tree form,
  so as to visualize the directory hierarchy similar to cmd.exe's built-in
  'tree' command, but with the added ability to exclude subtrees by directory
  names.

  NOTE: Symlinks to directories are not followed; a warning to that effect is
        issued.

  .PARAMETER Path
  The target directory path; defaults to the current directory.
  You may specify a wildcard pattern, but it must resolve to a single directory.

  .PARAMETER Exclude
  One or more directory names that should be excluded from the output; wildcards
  are permitted. Any directory that matches anywhere in the target hierarchy
  is excluded, along with its subtree.
  If -IncludeFiles is also specified, the exclusions are applied to the files'
  names as well.

  .PARAMETER IncludeFiles
  By default, only directories are printed; use this switch to print files
  as well.

  .PARAMETER Ascii
  Uses ASCII characters to visualize the tree structure; by default, graphical
  characters from the OEM character set are used.

  .PARAMETER IndentCount
  Specifies how many characters to use to represent each level of the hierarchy.
  Defaults to 4.

  .PARAMETER Force
  Includes hidden items in the output; by default, they're ignored.

  .NOTES
  Directory symlinks are NOT followed, and a warning to that effect is issued.

  .EXAMPLE
  tree

  Prints the current directory's subdirectory hierarchy.

  .EXAMPLE
  tree ~/Projects -Ascii -Force -Exclude node_modules, .git

  Prints the specified directory's subdirectory hierarchy using ASCII characters
  for visualization, including hidden subdirectories, but excluding the
  subtrees of any directories named 'node_modules' or '.git'.

  #>

    [cmdletbinding(PositionalBinding=$false)]
    param(
      [parameter(Position=0)]
      [string] $Path = '.',
      [string[]] $Exclude,
      [ValidateRange(1, [int]::maxvalue)]
      [int] $IndentCount = 4,
      [switch] $Ascii,
      [switch] $Force,
      [switch] $IncludeFiles
    )

    # Embedded recursive helper function for drawing the tree.
    function _tree_helper {

      param(
        [string] $literalPath,
        [string] $prefix
      )

      # Get all subdirs. and, if requested, also files.
      $items = Get-ChildItem -Directory:(-not $IncludeFiles) -LiteralPath $LiteralPath -Force:$Force

      # Apply exclusion filter(s), if specified.
      if ($Exclude -and $items) {
        $items = $items.Where({ $name = $_.Name; -not $Exclude.Where({ $name -like $_ }, 'First') })
      }

      if (-not $items) { return } # no subdirs. / files, we're done

      $i = 0
      foreach ($item in $items) {
        $isLastSibling = ++$i -eq $items.Count
        # Print this dir.
        $prefix + $(if ($isLastSibling) { $chars.last } else { $chars.interior }) + $chars.hline * ($indentCount-1) + $item.Name
        # Recurse, if it's a subdir (rather than a file).
        if ($item.PSIsContainer) {
          if ($item.LinkType) { Write-Warning "Not following dir. symlink: $item"; continue }
          $subPrefix = $prefix + $(if ($isLastSibling) { $chars.space * $indentCount } else { $chars.vline + $chars.space * ($indentCount-1) })
          _tree_helper $item.FullName $subPrefix
        }
      }
    } # function _tree_helper

    # Hashtable of characters used to draw the structure
    $ndx = [bool] $Ascii
    $chars = @{
      interior = ('├', '+')[$ndx]
      last = ('└', '\')[$ndx]                                                                #'
      hline = ('─', '-')[$ndx]
      vline = ('│', '|')[$ndx]
      space = ' '
    }

    # Resolve the path to a full path and verify its existence and expected type.
    $literalPath = (Resolve-Path $Path).Path
    if (-not $literalPath -or -not (Test-Path -PathType Container -LiteralPath $literalPath) -or $literalPath.count -gt 1) { throw "'$Path' must resolve to a single, existing directory."}

    # Print the target path.
    $literalPath

    # Invoke the helper function to draw the tree.
    _tree_helper $literalPath

  }

这篇关于打印目录树,但排除Windows cmd上的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆