如何编写PowerShell函数来获取目录?
使用 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 }
}
}
How can I remove the if
statements from my Get-Directories function or is this a better way去做吗?
Using PowerShell I can get the directories with the following command:
Get-ChildItem -Path $path -Include "obj" -Recurse | `
Where-Object { $_.PSIsContainer }
I would prefer to write a function so the command is more readable. For example:
Get-Directories -Path "Projects" -Include "obj" -Recurse
And the following function does exactly that except for handling -Recurse
elegantly:
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 }
}
}
How can I remove the if
statement from my Get-Directories function or is this a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
这有效,因为 -Recurse:$false 与根本没有 -Recurse 相同。
Try this:
This works because -Recurse:$false is the same has not having -Recurse at all.
在 PowerShell 3.0 中,它是通过
-File
-Directory
开关内置的:In PowerShell 3.0, it is baked in with
-File
-Directory
switches:奥辛给出的答案是正确的。我只是想补充一点,这几乎是想成为一个代理功能。如果您安装了PowerShell Community Extensions 2.0,则已经拥有此代理功能。您必须启用它(默认情况下禁用)。只需编辑 Pscx.UserPreferences.ps1 文件并更改此行,将其设置为 $true,如下所示:
请注意有关动态参数的限制。现在,当您导入 PSCX 时,请执行以下操作:
现在您可以执行以下操作:
The answer Oisin gives is spot on. I just wanted to add that this is skirting close to wanting to be a proxy function. If you have the PowerShell Community Extensions 2.0 installed, you already have this proxy function. You have to enable it (it is disabled by default). Just edit the Pscx.UserPreferences.ps1 file and change this line so it is set to $true as shown below:
Note the limitation regarding dynamic parameters. Now when you import PSCX do it like so:
Now you can do this: