【问题标题】:How to write a PowerShell function to get directories?如何编写 PowerShell 函数来获取目录?
【发布时间】:2011-03-17 06:25:27
【问题描述】:

使用 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 语句,或者这是更好的方法吗?

【问题讨论】:

  • 考虑使用 -Filter 而不是 -Include ,除非您需要包含多个项目。对于 *.txt 之类的内容,-Filter 可以明显更快。或者您可以随时添加两者。

标签: powershell directory get-childitem


【解决方案1】:

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

dir -Directory #List only directories
dir -File #List only files

【讨论】:

  • Get-ChildItem -Directory
【解决方案2】:

Oisin 给出的答案是正确的。我只是想补充一点,这与想要成为代理功能很接近。如果你安装了PowerShell Community Extensions 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

【讨论】:

  • 感谢 PowerShell 社区扩展的提醒。我可以用它作为参考。由于这是构建过程的一部分,我将坚持现有的,因为我不想添加另一个依赖项。
【解决方案3】:

试试这个:

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

【讨论】:

  • 感谢您的回答以及修复函数名称和参数声明的额外努力。学到的比我问的要多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
相关资源
最近更新 更多