您可以在 Powershell cmdlet 调用中动态设置属性吗?

Ric*_*rdo 1 parameters powershell powershell-cmdlet

我不确定这是否可行,但我想知道在 Powershell 中使用 cmdlet 时是否有一种优雅的“动态”方式来使用或不使用属性。

例如,在下面的代码中,我如何-directory根据某些条件将属性设置为存在或不存在?

gci $folder_root -recurse -directory | ForEach{ 
  # do something
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

您可以通过称为splatting 的技术有条件地将参数参数添加到调用中。

您需要做的就是构造一个类似字典的对象,并添加您可能想要传递给调用的任何参数:

# Create empty hashtable to hold conditional arguments
$optionalArguments = @{}

# Conditionally add an argument
if($somethingThatMightBeTrue){
    # This is equivalent to having the `-Directory` switch present
    $optionalArguments['Directory'] = $true
}

# And invoke the command
Get-ChildItem $folder_root -Recurse @optionalArguments
Run Code Online (Sandbox Code Playgroud)

请注意,我们splat的任何变量都是用 a 指定的,@而不是$在调用站点处指定的。