使用 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/