You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化PowerShell目录树脚本:移除临时文件及修复.gitignore排除失效问题

优化PowerShell目录树脚本(show-tree.ps1)

一、移除临时文件依赖,直接过滤冗余输出

原脚本通过临时文件过滤PSTree模块输出的空行、Source信息,效率低下。可直接通过管道在内存中完成过滤,无需磁盘IO操作:

# 直接通过管道过滤冗余行,替代临时文件读写
Get-PSTree -Path $PSScriptRoot | 
    Where-Object { $_ -notmatch '^Source:' -and $_ -notmatch '^\s*$' } |
    Out-Host

核心逻辑:

  • 用Where-Object直接排除以Source:开头的行和空行
  • 所有操作在管道中完成,避免临时文件的创建、读取、删除开销

二、正确解析.gitignore并应用排除规则

原Exclude参数未生效,原因是未正确转换.gitignore规则为PowerShell可识别的匹配模式。以下是完整的规则解析与过滤实现:

完整优化脚本

<#
.SYNOPSIS
打印脚本所在目录的树形结构,自动应用.gitignore排除规则
#>

# 获取脚本所在根目录
$rootDir = $PSScriptRoot

# 读取并解析.gitignore规则
$gitignoreRules = @()
$gitignorePath = Join-Path $rootDir ".gitignore"
if (Test-Path $gitignorePath) {
    $gitignoreRules = Get-Content $gitignorePath |
        # 过滤注释行和空行
        Where-Object { $_ -notmatch '^#' -and $_ -notmatch '^\s*$' } |
        ForEach-Object {
            $rule = $_.Trim()
            # 处理.gitignore中的目录规则(移除末尾的/)
            if ($rule -endsWith '/') { $rule.Substring(0, $rule.Length - 1) }
            else { $rule }
        }
}

# 生成树形结构并应用双重过滤
Get-PSTree -Path $rootDir |
    # 过滤模块自带的冗余行
    Where-Object { $_ -notmatch '^Source:' -and $_ -notmatch '^\s*$' } |
    # 过滤.gitignore指定的目录/文件
    Where-Object {
        $currentLine = $_
        # 正则转义规则字符,避免特殊符号(如.venv中的.)干扰匹配
        $excludeMatch = $gitignoreRules | Where-Object { $currentLine -match [regex]::Escape($_) }
        -not $excludeMatch
    } |
    Out-Host

关键优化点

  1. 规则解析:自动过滤.gitignore中的注释、空行,转换目录规则(移除末尾/),确保PowerShell能正确识别
  2. 精准匹配:用[regex]::Escape()转义规则中的特殊字符,避免像.venv里的.被当作通配符处理
  3. 链式过滤:先过滤模块冗余输出,再应用.gitignore规则,逻辑清晰且高效

内容的提问来源于stack exchange,提问作者Muhammad Ikhwan Perwira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:10:12