在PowerShell中,将“Get-ChildItem”命令的“recurse”参数用作参数。

9
我希望创建一个函数,可以切换在cmdlet Get-ChildItem中递归的能力。
作为一个非常基本的示例:
...

param 
(   
    [string] $sourceDirectory = ".",
    [string] $fileTypeFilter = "*.log",
    [boolean] $recurse = $true
)

Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter | 

...

如何在不使用if/else语句的情况下有条件地添加-recurse标志到Get-ChildItem中?
我认为可以将Get-ChildItem语句中的-recurse替换为$recurseText参数(如果$recurse为真,则设置为“-recurse”),但似乎不起作用。
4个回答

13
这里有几个问题。首先,你不应该使用 [boolean] 来定义 recurse 参数的类型。这需要在脚本中为 Recurse 参数传递一个参数,例如 -Recurse $true。你需要使用 [switch] 参数,如下所示。另外,在将开关值转发到 Get-ChildItem 的 -Recurse 参数时,使用 如下所示:
param (
    [string] $sourceDirectory = ".",
    [string] $fileTypeFilter = "*.log",
    [switch] $recurse
)

get-childitem $sourceDirectory -recurse:$recurse -filter $fileTypeFilter | ...

6
这个问题在PowerShell V1中的解决方法是使用其他答案中描述的方法(-recurse:$recurse),但在V2中,有一种新机制称为splatting,可以更轻松地将参数从一个函数传递到另一个函数。
Splatting允许您将字典或参数列表传递给PowerShell函数。以下是一个快速示例。
$Parameters = @{
    Path=$home
    Recurse=$true
}
Get-ChildItem @Parameters

在每个函数或脚本中,您可以使用 $psBoundParameters 来获取当前绑定的参数。通过向 $psBoundParameters 添加或删除项目,您可以轻松地使用函数的参数调用 cmdlet。
希望这能有所帮助。

2

我之前问过一个类似的问题... 我接受的答案基本上是在 PowerShell 的 v1 版本中,只需像这样传递命名参数:

get-childitem $sourceDirectory -recurse:$recurse -filter ...

不幸的是,在v1中似乎无法工作,它似乎将其视为下一个参数。get-childitem -recurse $true Get-ChildItem:无法找到路径'C:\src\True',因为它不存在。 - Sean
抱歉;使用“:”将两个内容连接在一起。 - John Weldon

0

这里有一个很好的参数类型列表:

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)
    )

这里开始


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接