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

标签 powershell directory get-childitem

使用 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 - 如何编写PowerShell函数来获取目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3270337/

相关文章:

powershell - Powershell 和 PSake 从哪里执行 msbuild?

c# - 从事件处理程序报告 Powershell 进度

Python: Pyinstaller on mac 当前目录问题

directory - 从 gradle 中的构建目录运行脚本

powershell - 如何限制 Get-ChildItem 搜索的文件(或限制递归深度)?

powershell - 如何在点源时调用全局命令

带条件的 PowerShell switch 语句

php - 在 Php 中使用德语变音符号创建目录

Powershell:为什么 (gci c:\ddd).count on an Empty 文件夹不返回 0

powershell - 排除 Get-ChildItem 中的连接点