代码之家  ›  专栏  ›  技术社区  ›  Tim Murphy

如何编写PowerShell函数来获取目录?

  •  10
  • Tim Murphy  · 技术社区  · 16 年前

    Get-ChildItem -Path $path -Include "obj" -Recurse | `
        Where-Object { $_.PSIsContainer }
    

    我更喜欢写一个函数,这样命令更可读。例如:

    Get-Directories -Path "Projects" -Include "obj" -Recurse
    

    下面的函数除了处理 -Recurse 优雅地:

    Function Get-Directories([string] $path, [string] $include, [boolean] $recurse)
    {
        if ($recurse)
        {
            Get-ChildItem -Path $path -Include $include -Recurse | `
                Where-Object { $_.PSIsContainer }
        }
        else
        {
            Get-ChildItem -Path $path -Include $include | `
                Where-Object { $_.PSIsContainer }
        }
    }
    

    如何移除 if 我的Get Directories函数中的语句,或者这是一个更好的方法吗?

    3 回复  |  直到 10 年前
        1
  •  13
  •   x0n    16 年前

    试试这个:

    # nouns should be singular unless results are guaranteed to be plural.
    # arguments have been changed to match cmdlet parameter types
    Function Get-Directory([string[]]$path, [string[]]$include, [switch]$recurse) 
    { 
        Get-ChildItem -Path $path -Include $include -Recurse:$recurse | `
             Where-Object { $_.PSIsContainer } 
    } 
    

    这是因为-Recurse:$false与没有-Recurse是相同的。

        2
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    -File -Directory 开关:

    dir -Directory #List only directories
    dir -File #List only files
    
        3
  •  2
  •   Keith Hill    16 年前

    奥辛给出的答案是正确的。我只想补充一点,这几乎是一个代理函数。如果你有 PowerShell Community Extensions

    GetChildItem = $true # Adds ContainerOnly and LeafOnly parameters 
                         # but doesn't handle dynamic params yet.
    

    注意有关动态参数的限制。现在,当您导入PSCX时,请执行以下操作:

    Import-Module Pscx -Arg [path to Pscx.UserPreferences.ps1]
    

    Get-ChildItem . -r Bin -ContainerOnly