Get-ChildItem 在 PowerShell 中递归作为参数
我希望创建一个可以在 cmdlet Get-ChildItem。
作为一个非常基本的示例:
...
param
(
[string] $sourceDirectory = ".",
[string] $fileTypeFilter = "*.log",
[boolean] $recurse = $true
)
Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter |
...
如何有条件地将 -recurse
标志添加到 Get-ChildItem 而无需诉诸某些 if/else 语句?
我想也许可以用 $recurseText
参数替换 Get-ChildItem 语句中的 -recurse
(如果 $recurse 为 true,则设置为“-recurse”),但是这似乎不起作用。
I am looking to create a function that could toggle the ability to recurse in cmdlet Get-ChildItem.
As a very basic example:
...
param
(
[string] $sourceDirectory = ".",
[string] $fileTypeFilter = "*.log",
[boolean] $recurse = $true
)
Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter |
...
How does one conditionally add the -recurse
flag to Get-ChildItem without having to resort to some if/else statement?
I thought perhaps one could just substitute the -recurse
in the Get-ChildItem statement with a $recurseText
parameter (set to "-recurse" if $recurse were true), but that does not seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有几件事。首先,您不想使用 [boolean] 作为递归参数的类型。这要求您在脚本上传递 Recurse 参数的参数,例如
-Recurse $true
。您想要的是一个 [switch] 参数,如下所示。此外,当您将开关值转发到 Get-ChildItem 上的 -Recurse 参数时,请使用:
,如下所示:A couple of things here. First, you don't want to use [boolean] for the type of the recurse parameter. That requires that you pass an argument for the Recurse parameter on your script e.g.
-Recurse $true
. What you want is a [switch] parameter as shown below. Also, when you forward the switch value to the -Recurse parameter on Get-ChildItem use a:
as shown below:PowerShell V1 解决此问题的方法是使用其他答案中描述的方法 (-recurse:$recurse),但在 V2 中,有一种名为 splatting 可以更轻松地将参数从一个函数传递到另一个函数。
Splatting 允许您将字典或参数列表传递给 PowerShell 函数。这是一个简单的例子。
在每个函数或脚本内部,您可以使用 $psBoundParameters 来获取当前绑定的参数。通过向
$psBoundParameters
添加或删除项目,可以轻松获取当前函数并使用某些函数的参数调用 cmdlet。我希望这有帮助。
The PowerShell V1 way to approach this is to use the method described in the other answers (-recurse:$recurse), but in V2 there is a new mechanism called splatting that can make it easier to pass the arguments from one function to another.
Splatting will allow you to pass a dictionary or list of arguments to a PowerShell function. Here's a quick example.
Inside of each function or script you can use
$psBoundParameters
to get the currently bound parameters. By adding or removing items to$psBoundParameters
, it's easy to take your current function and call a cmdlet with some the functions' arguments.I hope this helps.
我之前问过一个类似的问题...我接受的答案基本上是在PowerShell v1中,只是传递命名参数,如下所示:
I asked a similar question before... My accepted answer was basically that in v1 of PowerShell, just passing the named parameter through like:
以下是您可以使用的参数类型的详细列表:
来自 此处
Here's a good list of the types of parameters you can use:
From here