使用 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 函数中的语句还是这是更好的方法?

有帮助吗?

解决方案

试试:

# 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是相同的,也不是 - 根本没有。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top