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

使用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 }
    }
}
如何从我的Get-Directories功能中删除
if
语句,或者这是更好的方法吗?     
已邀请:
试试这个:
# 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。     
在PowerShell 3.0中,它使用
-File
-Directory
开关进行烘烤:
dir -Directory #List only directories
dir -File #List only files
    
Oisin给出的答案就是现场。我只想补充一点,这就是想要成为代理功能。如果安装了PowerShell社区扩展2.0,则您已拥有此代理功能。您必须启用它(默认情况下禁用)。只需编辑Pscx.UserPreferences.ps1文件并更改此行,使其设置为$ true,如下所示:
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
    

要回复问题请先登录注册