10

使用 PowerShell 我可以使用以下命令获取目录:

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 函数中删除该语句,或者这是一种更好的方法?

4

3 回答 3

13

Try this:

# 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 } 
} 

This works because -Recurse:$false is the same has not having -Recurse at all.

于 2010-07-17T05:26:17.067 回答
4

在 PowerShell 3.0 中,它与-File -Directory开关一起烘焙:

dir -Directory #List only directories
dir -File #List only files
于 2013-01-24T21:18:00.913 回答
2

The answer Oisin gives is spot on. I just wanted to add that this is skirting close to wanting to be a proxy function. If you have the PowerShell Community Extensions 2.0 installed, you already have this proxy function. You have to enable it (it is disabled by default). Just edit the Pscx.UserPreferences.ps1 file and change this line so it is set to $true as shown below:

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

Note the limitation regarding dynamic parameters. Now when you import PSCX do it like so:

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

Now you can do this:

Get-ChildItem . -r Bin -ContainerOnly
于 2010-07-17T16:57:18.793 回答