如何编写PowerShell函数来获取目录?
-
17-09-2020 - |
题
使用 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是相同的,也不是 - 根本没有。
其他提示
在 PowerShell 3.0 中,它被嵌入到 -File
-Directory
开关:
dir -Directory #List only directories
dir -File #List only files
答案Oisin给出了现货。我只是想补充一点,这是令人靠近想要成为代理功能的镜头。如果您拥有 2.0安装,则已安装此代理功能。您必须启用它(默认情况下禁用)。只需编辑pscx.userpreferences.ps1文件并更改此行,因此它设置为$ true,如下所示:
GetChildItem = $true # Adds ContainerOnly and LeafOnly parameters
# but doesn't handle dynamic params yet.
.
Import-Module Pscx -Arg [path to Pscx.UserPreferences.ps1]
.
Get-ChildItem . -r Bin -ContainerOnly
. 不隶属于 StackOverflow