[英]Get-ChildItem recurse as a parameter in PowerShell
我期待创建一个函数,可以切换cmdlet Get-ChildItem中递归的能力。
作为一个非常基本的例子:
...
param
(
[string] $sourceDirectory = ".",
[string] $fileTypeFilter = "*.log",
[boolean] $recurse = $true
)
Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter |
...
如何有条件地将-recurse
标志添加到Get-ChildItem而不必求助于某些if / else语句?
我想也许有可能只是替代-recurse
在Get-ChildItem声明以$recurseText
参数(设置为“-recurse”如果$递归是真实的),但似乎并没有工作。
这里有几件事。 首先,您不希望将[boolean]用于recurse参数的类型。 这要求您在脚本上传递Recurse参数的参数,例如-Recurse $true
。 你想要的是[switch]参数,如下所示。 此外,当您将开关值转发到Get-ChildItem上的-Recurse参数时,请使用:
如下所示:
param (
[string] $sourceDirectory = ".",
[string] $fileTypeFilter = "*.log",
[switch] $recurse
)
get-childitem $sourceDirectory -recurse:$recurse -filter $fileTypeFilter | ...
PowerShell V1的方法是使用其他答案中描述的方法(-recurse:$ recurse),但在V2中有一种称为splatting的新机制,可以更容易地将参数从一个函数传递到另一个函数。
Splatting允许您将字典或参数列表传递给PowerShell函数。 这是一个简单的例子。
$Parameters = @{
Path=$home
Recurse=$true
}
Get-ChildItem @Parameters
在每个函数或脚本中,您可以使用$psBoundParameters
来获取当前绑定的参数。 通过向$psBoundParameters
添加或删除项目,可以轻松获取当前函数并使用某些函数参数调用cmdlet。
我希望这有帮助。
之前我问了一个类似的问题 ...我接受的答案基本上是在PowerShell的v1中,只是将命名参数传递给:
get-childitem $sourceDirectory -recurse:$recurse -filter ...
以下是您可以使用的参数类型的良好列表:
param(
[string] $optionalparam1, #an optional parameter with no default value
[string] $optionalparam2 = "default", #an optional parameter with a default value
[string] $requiredparam = $(throw ""requiredparam required."), #throw exception if no value provided
[string] $user = $(Read-Host -prompt "User"), #prompt user for value if none provided
[switch] $switchparam; #an optional "switch parameter" (ie, a flag)
)
从这里开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.